Le *_*con 6 unit-testing sinon meteor
假设我有两个函数,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;
Run Code Online (Sandbox Code Playgroud)
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);
});
});
Run Code Online (Sandbox Code Playgroud)
以下代码有效,但是重新定义foo是否正确?
更新
另外,不可能以此方式创建模拟或存根,这使我认为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
});
});
Run Code Online (Sandbox Code Playgroud)
这是如何用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
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1887 次 |
| 最近记录: |