假设我有两个函数,foo
在bar
中调用。我有一个流星应用程序,所以我决定使用流星mocha
包与sinon
和chai
而不是jest
// foo.js
const foo = () => // call to a google maps api;
export default foo;
// bar.js
const bar = (x) => {
foo();
...
};
export default bar;
在这种情况下,模拟foo
的正确方法是什么?
目前我已经提出了以下解决方案:
import foo from 'path/to/foo.js'
import bar from 'path/to/bar.js'
describe('my test suite', function() {
it('should pass the test', function() {
foo = spy();
bar(5);
assert(foo.calledOnce);
});
});
以下代码有效,但重新定义foo
是否正确?
UPDATE
此外,不可能以这种方式创建模拟或存根,这让我觉得Sinon不适合模拟独立功能
Sinon
适用于独立的JavaScript函数。
以下是如何在Sinon
间谍中包装模块的默认导出的示例:
import * as sinon from 'sinon';
import * as fooModule from 'path/to/foo.js'
import bar from 'path/to/bar.js'
describe('my test suite', function() {
it('should pass the test', function() {
const spy = sinon.spy(fooModule, 'default'); // wrap the function in a spy
bar(5);
assert(spy.calledOnce); // SUCCESS
spy.restore(); // restore the original function
});
});
以下是如何使用Sinon
存根替换模块的默认导出的示例:
import * as sinon from 'sinon';
import * as fooModule from 'path/to/foo.js'
import bar from 'path/to/bar.js'
describe('my test suite', function() {
it('should pass the test', function() {
const stub = sinon.stub(fooModule, 'default').returns('something else'); // stub the function
bar(5); // foo() returns 'something else' within bar(5)
assert(stub.calledOnce); // SUCCESS
stub.restore(); // restore the original function
});
});