Ami*_*spi 5 mocha.js sinon chai redux redux-thunk
我正在尝试使用mocha,chai和sinon(我的第一次!)测试我的asyn thunk中间件功能.
请考虑我的文件:
ayncActionCreators.js
export const fetchCurrentUser = () => {
return (dispatch) => {
setTimeout(dispatch, 100);
}
};
Run Code Online (Sandbox Code Playgroud)
ayncActionCreators.spec.js
//...
it('Should work', () => {
const dispatch = sinon.spy();
const action = fetchCurrentUser();
action(dispatch);
expect(dispatch.called).to.be.true;
});
Run Code Online (Sandbox Code Playgroud)
我还没有实现fetchCurrentUser函数 - 只是假设它需要一些"服务器"时间然后它将调用'dispatch()'.
由于异步流,规范失败.如果我在期望之前添加一个101毫秒的setTimeout - 它会通过.
我的代码将使用一些返回promise的DB API,因此async函数最终将如下所示:
//...
return (dispatch) => {
return dbAPI.fetchUser().then(dispatch(....));
}
Run Code Online (Sandbox Code Playgroud)
所以我试图要求dbAPI并在测试中创建一个sinon.stub().returns(Promise.resolve())并且它也不能正常工作(我认为,因为存根返回一个已解析的promise - 异步函数将像一个同步功能).
任何想法我应该如何测试这样的异步函数?
谢谢,阿米特.
不要用sinon模仿调度,自己编写并done()在完成后调用Mocha .
it('Should work', (done) => {
const dispatch = () => {
// Do your tests here
done();
};
const action = fetchCurrentUser();
action(dispatch)
// Also allow quick failures if your promise fails
.catch(done);
})
Run Code Online (Sandbox Code Playgroud)
如果您只是想确保调用调度,那么mocha将超时.来自异步操作创建者的返回承诺的捕获允许错误显示在正确的位置,并且测试失败而不是超时.
好吧,我想我已经找到了解决方案:
假设我的异步函数如下所示:
//...
return (dispatch) => {
return dbAPI.fetchUser().then(dispatch(....));
}
Run Code Online (Sandbox Code Playgroud)
然后我可以编写规范如下:
it('Should work', () => {
dbAPI.fetchUser = sinon.stub().returns(Promise.resolve({username: 'John'}));
const dispatch = sinon.spy();
const action = fetchCurrentUser();
action(dispatch).then(() => {
expect(dispatch.called).to.be.true;
});
});
Run Code Online (Sandbox Code Playgroud)
我不知道这是否是一种解决方法,但它确实有效。我很感激您对更好的方法的意见......
谢谢,阿米特。
| 归档时间: |
|
| 查看次数: |
3340 次 |
| 最近记录: |