Sinon Spy for Non-Class Methods

问题描述 投票:1回答:1

我在一个名为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个回答
0
投票

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"

© www.soinside.com 2019 - 2024. All rights reserved.