【问题标题】:Sinon Spy for Non-Class Methods非类方法的 Sinon Spy
【发布时间】:2019-09-11 05:43:27
【问题描述】:

我在一个名为 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]);
  });
});

【问题讨论】:

    标签: javascript mocking sinon stubbing


    【解决方案1】:

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

    ...通常对象是一个模块,而属性是模块导出的一个函数

    当函数的模块导出被存根时,任何调用函数的模块导出的代码都会调用存根。


    不可能在上面的代码中存根someFunction,因为processListOfItems 没有调用someFunction模块导出,而是直接调用someFunction

    processListOfItems 需要调用someFunction模块导出 以便能够存根调用。


    这里有一个简单的例子来演示如何使用 Node.js 模块语法:

    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 模块语法的简单示例:

    util.js

    import * as util from './util';  // <= import module into itself
    
    export const func1 = () => {
      return 'hello ' + util.func2();  // <= use the module
    }
    
    export const func2 = () => 'world';
    

    util.test.js

    import * as sinon from 'sinon';
    import * as util from './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"

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 2017-09-19
      • 2017-01-07
      • 2012-11-13
      • 2015-11-26
      • 2020-10-21
      相关资源
      最近更新 更多