我有一个 Redux 操作,它本身会分派(dispatch)另外两个操作。每个 Action 都是从导入的函数中检索的。一个来自本地模块,另一个来自外部库。
import { functionA } from './moduleA';
import { functionB } from 'libraryB';
export function myAction() {
return (dispatch) => {
dispatch(functionA());
...
dispatch(functionB());
}
}
在我的测试中,我使用的是
sinon
沙箱来 stub 函数,但只有两个测试通过。我希望这三个都能通过。import * as A from './moduleA';
import * as B from 'libraryB';
describe(__filename, async () => {
it('Calls 2 other actions', () => {
sandbox = sinon.sandbox.create();
const dispatch = sandbox.stub();
sandbox.stub(A, 'functionA');
sandbox.stub(B, 'functionB');
await myAction()(dispatch);
// passes
expect(dispatch.callCount).to.equal(2);
//passes
expect(A.functionA).to.have.been.called();
// fails
expect(B.functionB).to.have.been.called();
});
});
最后一个期望因错误而失败:
TypeError: [Function: functionB] is not a spy or a call to a spy!
当我将函数输出到控制台时,我得到了这个,这似乎与 Babel 导入导出导出的方式有关
(ES6 re-exported values are wrapped into Getter)。这些功能可以实时工作,而不是在测试中。
{ functionA: [Function: functionA] }
{ functionB: [Getter] }
我试过使用
stub.get(getterFn)
但这只是给了我错误:TypeError: Cannot redefine property: fetchTopicAnnotations
最佳答案
你试过命名你的 stub 吗?你的代码读起来有点奇怪。您在测试中的任何时候都没有提到您的 stub 。
import * as A from './moduleA';
import * as B from 'libraryB';
describe(__filename, async () => {
it('Calls 2 other actions', () => {
sandbox = sinon.sandbox.create();
const dispatch = sandbox.stub();
const functionAStub = sandbox.stub(A, 'functionA');
const functionBStub = sandbox.stub(B, 'functionB');
await myAction()(dispatch);
// passes
expect(dispatch.callCount).to.equal(2);
//passes
expect(functionAStub.called).toBe(true);
// fails
expect(functionBStub.called).toBe(true);
});
});
关于javascript - 无法使用 Sinon stub 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361748/