【问题标题】:can we replace multiple methods of same resource, in sinun.stub我们可以在 sinun.stub 中替换同一资源的多个方法吗
【发布时间】:2021-10-19 17:46:19
【问题描述】:

我们能否在一个测试用例中替换同一资源的多个方法

it('should render', () => {
    // first replace
    sinon.stub(DBInstance.getCollection(), 'find').returns({});

    //second replace
    sinon.stub(DBInstance.getCollection(), 'findOne').returns({});
    ...
    ...
});

【问题讨论】:

  • 你期待什么?你得到了什么?

标签: javascript chai sinon


【解决方案1】:

是的,你可以。您可以先存储资源并存根,也可以使用资源原型存根。

这只是简单的检查代码,因为我不知道你使用的是什么模块。

// File: check.js
class Resource {
  find() { console.log('real find') }
  findOne() { console.log('real findOne') }
};

const check = {
  getCollection: () => {
    return new Resource();
  },
};

module.exports = { check, Resource };

这是一个测试文件,向您展示可以替换同一资源的多个方法。

// File: check.spec.js
const sinon = require('sinon');
const { expect } = require('chai');
const { check, Resource } = require('./check');

describe('stub check', () => {
  it('using stored resource', () => {
    // Store the resource first.
    const collection = check.getCollection();
    // Using the stored resource to stub it.
    sinon.stub(collection, 'find').returns({});
    sinon.stub(collection, 'findOne').returns({});
    expect(collection.find()).to.deep.equal({});
    expect(collection.findOne()).to.deep.equal({});
    sinon.restore();
  });

  it('using prototype resource', () => {
    // Using the prototype resource.
    sinon.stub(Resource.prototype, 'find').returns({});
    sinon.stub(Resource.prototype, 'findOne').returns({});
    expect(check.getCollection().find()).to.deep.equal({});
    expect(check.getCollection().findOne()).to.deep.equal({});
    sinon.restore();
  });
});

我从终端运行时的结果:

$ npx mocha check.spec.js 


  stub check
    ✓ using stored resource
    ✓ using prototype resource


  2 passing (4ms)

没有一个真正的方法被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2017-04-29
    • 2011-03-05
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    相关资源
    最近更新 更多