【发布时间】:2017-05-05 16:38:36
【问题描述】:
如何对自定义 redux 中间件进行单元测试?我有这个简单的函数,它应该在给定的超时后调度动作但是......我不知道如何处理它。关于这个问题,我没有找到足够的资源。
const callAPiTimeoutMiddleware = store => next => (action) => {
if (action[CALL_API]) {
if (action[CALL_API].onTimeout) {
setTimeout(() => {
store.dispatch({ type: action[CALL_API].onTimeout });
}, DEFAULT_TIMEOUT_LENGTH);
}
}
return next(action);
}
这些是我基于已接受答案中提到的博客文章的测试:
describe('callAPiTimeoutMiddleware', () => {
describe('With [CALL_API] symbol', () => {
it('should dispatch custom action', () => {
const clock = sinon.useFakeTimers();
const fakeStore = { dispatch: sinon.spy() };
const fakeNext = sinon.spy();
const fakeAction = {
[CALL_API]: {
endpoint: 'endPoint',
method: 'METHOD',
types: ['REQUEST_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE'],
onTimeout: 'TIMEOUT_TYPE',
},
};
callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction);
clock.tick(99000);
expect(fakeStore.dispatch.calledOnce).toEqual(true);
});
it('should call next action', () => {
const fakeStore = { dispatch: sinon.spy() };
const fakeNext = sinon.spy();
const fakeAction = {
[CALL_API]: {
endpoint: 'endPoint',
method: 'METHOD',
types: ['REQUEST_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE'],
onTimeout: 'TIMEOUT_TYPE',
},
};
callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction);
expect(fakeNext.calledOnce).toEqual(true);
});
});
describe('Without [CALL_API] symbol', () => {
it('should NOT dispatch anything', () => {
const clock = sinon.useFakeTimers();
const fakeStore = { dispatch: sinon.spy() };
const fakeNext = sinon.spy();
const fakeAction = { type: 'SOME_TYPE' };
callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction);
clock.tick(99000);
expect(fakeStore.dispatch.calledOnce).toEqual(false);
});
it('should call next action', () => {
const fakeStore = { dispatch: sinon.spy() };
const fakeNext = sinon.spy();
const fakeAction = { type: 'SOME_TYPE' };
callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction);
expect(fakeNext.calledOnce).toEqual(true);
});
});
});
【问题讨论】:
-
它是一个函数 - 像 Mocha、AVA、Jasmine 等通常的单元测试午餐器和像 Sinon 这样的模拟构建器或商店的手动模拟呢?
-
我真的不知道如何使用这些。 :(你能告诉我工作的例子吗?
标签: unit-testing reactjs asynchronous redux redux-thunk