I use fetch-mock, redux-mock-store, promise-middleware to test the redux implementation of my application. I have following code:
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();
});
});
});
The problem is that 404 call I am mocking with retchMock always ends up being resolved as ACTION_1_FULFILLED. why would this be the case? Am I mocking the call incorrectly?
Redux Promise Middleware always dispatches a rejected action when given a rejected action. If your mocked action always ends up being a fulfilled action, when you expect a rejected action, it is because the promise payload is fulfilled.
This can happen if you have any side-effects (e.g., any functions that use the
then
method on the promise) and don't properly pass the error up to the middleware. Without more context, though, it's impossible to give you a definitive answer. It would be helpful if you included yourhostNameSearchActions
.