如果该动作有重音和轴距,该如何开玩笑地测试该动作?

时间:2018-09-04 23:08:45

标签: reactjs redux jestjs

我正在尝试使用我的动作和减速器进行测试。我不明白这个问题,请帮忙。

这是我的动作

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

发生了什么事?

1 个答案:

答案 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)

 })

有关moxiossee this link

的更多信息