如何sinon间谍模块导出实用程序功能 [英] How to sinon spy module export utility functions
问题描述
在javascript(ES6)中,我有一个实用程序模块,它只包含一些函数,然后在文件的最后,我这样导出它们:
In javascript (ES6), I have a utility module which just contains some functions, and then in the end of the file, I export them like so:
module.exports = {
someFunction1,
someFunction2,
someFunction3,
}
然后我想为这些函数编写单元测试。一些功能相互依赖;他们以某种方式相互调用,例如,someFunction1可能会调用someFunction2。没有循环问题。
Then I want to write unit tests for those functions. Some of the functions depend on each other; they call each other in a way, that for example, someFunction1 might call someFunction2. There's no circular problems.
一切正常,直到我需要监视其中一个函数被调用。我该怎么做?目前我正在使用Chai和Sinon。
Everything works well, until I need to spy that one of the functions is called. How can I do it? Currently I'm using Chai and Sinon.
在测试文件中,我将整个文件作为模块导入:
In the test file, I have imported the whole file as a module:
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的一个例子:
The problem is, that the test fails, because in someFunction1, the someFunction2 function is used directly. I apply the spy to the module object's function. But that's a different object. Here's an example of the someFunction1:
function someFunction1() {
someFunction2()
return 2;
}
我知道它不起作用的原因,但我不知道知道在这种情况下最好的做法是什么?请帮助!
I know the reason why it won't work, but I don't know what would be the best practise in this case to make it work? Please help!
推荐答案
您可以使用重新布线模块。以下是一个示例:
You can use rewire module. Here is an example:
源代码:
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);
});
这篇关于如何sinon间谍模块导出实用程序功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!