我试图对文件中的一个函数进行单元测试,同时在SAME文件中存根另一个函数,但是未应用模拟程序,而是调用了real方法。这是一个例子:
// file: 'foo.js' export function a() { // ..... } export function b() { let stuff = a(); // call a // ...do stuff }
而我的测试:
import * as actions from 'foo'; const aStub = sinon.stub(actions, 'a').returns('mocked return'); actions.b(); // b() is executed, which calls a() instead of the expected aStub()
一些重组可以使这项工作。
我使用了commonJS语法。在ES6中也应以相同的方式工作。
foo.js
const factory = { a, b, } function a() { return 2; } function b() { return factory.a(); } module.exports = factory;
test.js
const ser = require('./foo'); const sinon = require('sinon'); const aStub = sinon.stub(ser, 'a').returns('mocked return'); console.log(ser.b()); console.log(aStub.callCount);
输出量
模拟回报 1个
模拟回报
1个