Sinon Spy非类方法

时间:2019-04-21 23:02:38

标签: javascript mocking sinon stubbing

我在一个名为utils.js的文件中有一个包含一堆util函数的javascript文件

export const processListOfItems = (input): [] => {
  let listOfItems = [];
  for (var index = 0; index < rawPayload.length; ++index) {
    listOfItems.push(someFunction(item));
  }
  return listOfItems;
};

someFunction也在utils.js中定义。

对于测试,我想存根“ someFunction”,但在弄清楚如何做到这一点时遇到了麻烦。看起来sinon.spy()可能是我想要的方法,但看起来它需要一个对象,因为它只是一个utils文件,所以我没有一个对象。

我理想的测试应该是这样

describe('someFunction fails on an item', () => {
  it('returns the array with the rest of the items', () => {
    const items = ['hi', 'hello'];

    // I want to make it such that, when we go into the getListOfItems code, we return 42 whenever we call someFunction, rather than going into the logic itself.
    const someFunctionStub = sinon.stub(someFunction).returns(42);

    expect(getListOfItems(items)).toEqual([42, 42]);
  });
});

1 个答案:

答案 0 :(得分:0)

sinon.stub替换对象上的属性...

...而且对象通常是 module ,而属性是模块导出的功能

对函数的模块导出进行存根时,任何调用该函数的 module export 的代码都将调用存根。


由于someFunction没有调用processListOfItems module export ,而是调用{ {1}}。

someFunction需要调用someFunction模块导出以便能够存入该调用。


这是一个使用Node.js模块语法进行演示的简单示例:

util.js

processListOfItems

util.test.js

someFunction

...这是一个使用ES6模块语法的简单示例:

util.js

exports.func1 = () => {
  return 'hello ' + exports.func2();  // <= use the module
}

exports.func2 = () => 'world';

util.test.js

const sinon = require('sinon');
const util = require('./util');

describe('func1', () => {
  it('should work', () => {
    const stub = sinon.stub(util, 'func2').returns('everyone');
    expect(util.func1()).toBe('hello everyone');  // Success!
  });
});

请注意,由于ES6模块"support cyclic dependencies automatically"可以导入自身。