我正在尝试使用我的动作和减速器进行测试。我不明白这个问题,请帮忙。
这是我的动作
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,
});
})
}
这是我的 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)
})
})
总是抛出错误Error: Network Error
发生了什么事?
答案 0 :(得分:3)
在使用axios
时,请考虑使用moxios
而非fetch-mock
来模拟网络请求。
要使用moxios
,只需在每次测试之前和之后安装和卸载moxios:
beforeEach(function () {
moxios.install()
})
afterEach(function () {
moxios.uninstall()
})
然后您可以在测试中为特定的请求URL提供模拟,如下所示:
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)
})
有关moxios
,see this link