reactjs - 如果某个 Action 有 thunk 和 axios,我如何用 jest 测试该 Action ?

标签 reactjs redux jestjs

我正在尝试使用 jest 来测试我的操作和 reducer 。我不明白这个问题,请帮忙。

这是我的行动:

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)
  })
})

总是抛出错误错误:网络错误

发生了什么事?

最佳答案

当您使用 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

关于reactjs - 如果某个 Action 有 thunk 和 axios,我如何用 jest 测试该 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52175064/

相关文章:

javascript - 如何将Material UI数据传递给Formik?

reactjs - 组件定义缺少显示名称react/display-name

reactjs - 发送 Action 后的 Redux Thunk 回调?

javascript - 在 redux 中在哪里调度多个 Action ?

javascript - 如何断言属性的呈现值?

javascript - React.render 错误

node.js - React-Router 5 和 Express - Catch-All 路由回退

javascript - 组件 props.dispatch 不起作用。 react 还原

reactjs - 使用 Jest 模拟 React 的 AJAX 请求

javascript - 使用 Jest 测试 React 应用程序时如何查询原生 html 元素?