gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:12:33 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com