Javascript 如何使用sinon spy module导出实用程序功能
在javascript(ES6)中,我有一个实用程序模块,其中只包含一些函数,然后在文件末尾,我将它们导出为:Javascript 如何使用sinon spy module导出实用程序功能,javascript,node.js,sinon,chai,Javascript,Node.js,Sinon,Chai,在javascript(ES6)中,我有一个实用程序模块,其中只包含一些函数,然后在文件末尾,我将它们导出为: module.exports = { someFunction1, someFunction2, someFunction3, } 然后我想为这些函数编写单元测试。有些功能相互依赖;它们以某种方式相互调用,例如,someFunction1可能调用someFunction2。没有循环问题 一切正常,直到我需要监视其中一个函数被调用为止。我怎么做?目前我正在使用柴和西农 在测
module.exports = {
someFunction1,
someFunction2,
someFunction3,
}
然后我想为这些函数编写单元测试。有些功能相互依赖;它们以某种方式相互调用,例如,someFunction1可能调用someFunction2。没有循环问题
一切正常,直到我需要监视其中一个函数被调用为止。我怎么做?目前我正在使用柴和西农
在测试文件中,我将整个文件作为一个模块导入:
const wholeModule = require('path/to/the/js/file')
最后,我的测试如下所示:
it('should call the someFunction2', (done) => {
const spy = sinon.spy(wholeModule, 'someFunction2')
wholeModule.someFunction1() // someFunction2 is called inside someFunction1
assert(spy.calledOnce, 'someFunction2 should be called once')
done()
})
问题是,测试失败,因为在someFunction1中,someFunction2函数是直接使用的。我将间谍应用于模块对象的函数。但那是另一个对象。下面是someFunction1的一个示例:
function someFunction1() {
someFunction2()
return 2;
}
我知道它不起作用的原因,但我不知道在这种情况下,什么是使它起作用的最佳实践?请帮忙 您可以使用模块。以下是一个例子:
源代码:
function someFunction1() {
console.log('someFunction1 called')
someFunction2();
}
function someFunction2() {
console.log('someFunction2 called')
}
module.exports = {
someFunction1: someFunction1,
someFunction2: someFunction2
}
'use strict';
var expect = require('chai').expect;
var rewire = require('rewire');
var sinon = require('sinon');
var funcs = rewire('../lib/someFunctions');
it('should call the someFunction2', () => {
var someFunction2Stub = sinon.stub();
funcs.__set__({
someFunction2: someFunction2Stub,
});
someFunction2Stub.returns(null);
funcs.someFunction1();
expect(someFunction2Stub.calledOnce).to.equal(true);
});
测试用例:
function someFunction1() {
console.log('someFunction1 called')
someFunction2();
}
function someFunction2() {
console.log('someFunction2 called')
}
module.exports = {
someFunction1: someFunction1,
someFunction2: someFunction2
}
'use strict';
var expect = require('chai').expect;
var rewire = require('rewire');
var sinon = require('sinon');
var funcs = rewire('../lib/someFunctions');
it('should call the someFunction2', () => {
var someFunction2Stub = sinon.stub();
funcs.__set__({
someFunction2: someFunction2Stub,
});
someFunction2Stub.returns(null);
funcs.someFunction1();
expect(someFunction2Stub.calledOnce).to.equal(true);
});
很好的尝试,但没有成功=/。它显然调用了伪函数。但是,当我断言间谍被召唤时,事实并非如此called@VilleMiekk-oja编辑后您是否尝试过该解决方案?是的,结果没有差异。我非常确定这与I module.export实用程序函数的方式有关。我的做法是在问题描述中。恭喜!您的上一个示例确实有效:)。请删除其余的,因为它们不起作用