Trying to test my async action creators using this example: http://redux.js.org/docs/recipes/WritingTests.html#async-action-creators and I think I did everything the same but I've got an error:
async actions › creates FETCH_BALANCE_SUCCEESS when fetching balance has been done
TypeError: store.dispatch(...).then is not a function
Don't understand why it's happened because I did everything from the example step by step.
I also found this example http://arnaudbenard.com/redux-mock-store/ but anyway, mistake exists somewhere and unfortunately, I can't find it. Where is my mistake, why I've got an error even If my test case looks like the same as an example
My test case:
import nock from 'nock';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from './';
import * as types from '../constants';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
afterEach(() => {
nock.cleanAll();
});
it('creates FETCH_BALANCE_SUCCEESS when fetching balance has been done', () => {
const store = mockStore({});
const balance = {};
nock('http://localhost:8080')
.get('/api/getbalance')
.reply(200, { body: { balance } });
const expectedActions = [
{ type: types.FETCH_BALANCE_REQUEST },
{ type: types.FETCH_BALANCE_SUCCEESS, body: { balance } },
];
return store.dispatch(actions.fetchBalanceRequest()).then(() => {
// return of async actions
expect(store.getActions()).toEqual(expectedActions);
});
});
});
My actions which I am trying to test.
import 'whatwg-fetch';
import * as actions from './actions';
import * as types from '../constants';
export const fetchBalanceRequest = () => ({
type: types.FETCH_BALANCE_REQUEST,
});
export const fetchBalanceSucceess = balance => ({
type: types.FETCH_BALANCE_SUCCEESS,
balance,
});
export const fetchBalanceFail = error => ({
type: types.FETCH_BALANCE_FAIL,
error,
});
const API_ROOT = 'http://localhost:8080';
const callApi = url =>
fetch(url).then(response => {
if (!response.ok) {
return Promise.reject(response.statusText);
}
return response.json();
});
export const fetchBalance = () => {
return dispatch => {
dispatch(actions.fetchBalanceRequest());
return callApi(`${API_ROOT}/api/getbalance`)
.then(json => dispatch(actions.fetchBalanceSucceess(json)))
.catch(error =>
dispatch(actions.fetchBalanceFail(error.message || error))
);
};
};
In your test you have
return store.dispatch(actions.fetchBalanceRequest()).then(() => { ... })
You're trying to test fetchBalanceRequest, which returns an object, so you cannot call .then() on that. In your tests, you would actually want to test fetchBalance, since that is an async action creator (and that is what is explained in the redux docs you posted).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With