我使用fetch-mock,redux-mock-store,promise-middleware来测试我的应用程序的redux实现。我有以下代码:
import configureMockStore from 'redux-mock-store';
import promiseMiddleware from 'redux-promise-middleware';
import fetchMock from 'fetch-mock';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { bindActionCreators } from 'redux';
import { ACTION_1, hostNameSearchActions }
from '../../../src/actions/hostNameSearchActions';
const middlewares = [thunk, promiseMiddleware(), createLogger()];
let mockStore = configureMockStore(middlewares);
const SERVICE_URL = 'http://url_to_the_service';
describe('Testing thunk actions', () => {
let store = mockStore({ hostData: { key1 :'value'} });
const aHostNameSearch = bindActionCreators({ ...hostNameSearchActions }, store.dispatch).hostNameSearch;
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
mockStore = configureMockStore(middlewares);
store = mockStore({ hostData: { key1 :'value'} });
});
it('ACTION_1_PENDING, ACTION_1_REJECTED dispatched, payload matches expected payload', (done) => {
fetchMock
.mock(`${SERVICE_URL}`,
404 );
const expectedActions = [
{ type: `${ACTION_1}_PENDING` },
{ type: `${ACTION_1}_REJECTED`, payload: {error: 'test.body.error.message'}}
];
aHostNameSearch().then(() => {
expect(store.getActions()).toEqual(expectedActions);
done();
});
});
});
问题是我用retchMock嘲笑的404调用总是最终被解析为ACTION_1_FULFILLED。为什么会这样呢?我是否错误地嘲笑了这个电话?
答案 0 :(得分:0)
Redux Promise中间件在给出被拒绝的操作时始终会调度被拒绝的操作。如果您的模拟操作总是最终成为一个已完成的操作,那么当您期望被拒绝的操作时,这是因为实现了promise负载。
如果您有任何副作用(例如,在承诺上使用then
方法的任何函数)并且没有将错误正确地传递给中间件,则会发生这种情况。但是,如果没有更多的背景,就无法给出明确的答案。如果您加入hostNameSearchActions
。