Mic*_*hal 12 unit-testing asynchronous reactjs redux redux-thunk
如何对自定义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);
}
Run Code Online (Sandbox Code Playgroud)
这些是基于博客文章的测试,在接受的答案中提到:
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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
我需要更多详细信息才能真正为中间件创建测试,所以这是我针对中间件测试的答案:
无需进行大量模拟即可非常轻松地测试中间件。链接的箭头函数看起来很吓人,但这仅取决于它们的调用方式。我用玩笑来帮助我测试,但是您可以用其他东西代替所有玩笑功能。我将直接进入代码并在注释中进行解释:
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);
Run Code Online (Sandbox Code Playgroud)
这就是您在测试中调用中间件的方式。在您的情况下,如果您要检查是否已调用调度,则可以执行以下操作:
// Add this in the beginning
store.dispatch = jest.fn();
// Add this after calling logger()
expect(store.dispatch.mock.calls).toEqual('whatever calls you expected');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5892 次 |
| 最近记录: |