如何对自定义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);
});
});
});
答案 0 :(得分:12)
redux-thunk
中间件已编写单元测试。您可以参考here
他只使用摩卡和柴。
而here他正在谈论如何为redux应用程序编写单元测试。
关于redux中间件的好blog以及如何为它们编写单元测试。
答案 1 :(得分:5)
我需要更多细节才能真正为中间件创建测试,所以这是我针对中间件测试的答案:
无需进行大量模拟即可非常轻松地测试中间件。链接的箭头函数看起来很吓人,但这仅取决于它们的调用方式。我用玩笑来帮助我测试,但是您可以用其他东西代替所有玩笑功能。我将直接进入代码并在注释中进行解释:
import logger from './logger'; //this is your middleware
const next = jest.fn(); // middleware needs those as parameters, usually calling next(action) at the end to proceed
const store = jest.fn();
const action = { type: 'YOUR_ACTION_TYPE', payload: { your: 'data' }}
logger(store)(next)(action);
这就是您在测试中如何调用中间件的方式。对于您的情况,如果要检查是否已调用调度,则可以执行以下操作:
// Add this in the beginning
store.dispatch = jest.fn();
// Add this after calling logger()
expect(store.dispatch.mock.calls).toEqual('whatever calls you expected');