Reputation: 403
I'm trying to test using jest my action and reducer. I don't understand the problem please help.
This is my action:
import { GET_TEXT } from './types';
import axios from 'axios';
export const getText = (text) => dispatch => {
let obj = {text: text};
const productsAPI = "http://192.168.0.22:3000/getText";
axios.post(productsAPI, obj)
.then(res => {
console.log(res)
dispatch({
type: GET_TEXT,
payload: res.data,
});
})
}
and this is my App.jest.test:
import * as action from './store/actions/textAction';
import * as types from './store/actions/types';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares)
console.log("Llegue hasta aqui");
describe('async actions', () => {
it('should dispatch actions of ConstantA and ConstantB', () => {
const expectedActions = {type: types.GET_TEXT, payload: 'Hola'};
const store = mockStore({})
store.dispatch(action.getText('Hola'));
expect(store.getActions()).toEqual(expectedActions)
})
})
Always throws an error Error: Network Error
What's happening?
Upvotes: 3
Views: 936
Reputation: 30370
As you're using axios
, consider using moxios
rather than fetch-mock
, to mock your network requests.
To use moxios
, you simply install, and uninstall moxios before and after each test:
beforeEach(function () {
moxios.install()
})
afterEach(function () {
moxios.uninstall()
})
You can then provide a mock for a particular request URL, in your test as follows:
it('should dispatch actions of ConstantA and ConstantB', () => {
const expectedActions = {type: types.GET_TEXT, payload: 'Hola'};
// Mock an end point and response for requests to /test
moxios.stubRequest('/test', {
status: 200,
responseText: 'the mocked result'
})
const expectedActions = {type: types.GET_TEXT, payload: 'Hola'};
const store = mockStore({})
store.dispatch(action.getText('Hola'));
expect(store.getActions()).toEqual(expectedActions)
})
For more information on moxios
, see this link
Upvotes: 3