如果此动作有thunk和axios,我如何用jest测试动作?

问题描述 投票:3回答:1

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

这是我的行动:

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

发生了什么?

reactjs redux jestjs
1个回答
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的更多信息

© www.soinside.com 2019 - 2024. All rights reserved.