Reactjs 单元测试异步redux操作时如何检索响应数据
我正在做这个测试,测试Reactjs 单元测试异步redux操作时如何检索响应数据,reactjs,redux,jestjs,enzyme,Reactjs,Redux,Jestjs,Enzyme,我正在做这个测试,测试getImagesaction函数。我犯了这个错误 ● 应该从操作函数获取图像›应该从 作用函数 expect(received).toEqual(expected) // deep equality Expected: {"data": {}, "type": "GET_IMAGES"} Received: [Function anonymous] 理想情况下,我希望在数据对象中传递响应数据。我如何才能成功地通过测试 imageActions import{GET_-
getImages
action函数。我犯了这个错误
● 应该从操作函数获取图像›应该从
作用函数
expect(received).toEqual(expected) // deep equality
Expected: {"data": {}, "type": "GET_IMAGES"}
Received: [Function anonymous]
理想情况下,我希望在数据对象中传递响应数据。我如何才能成功地通过测试
imageActions
import{GET_-IMAGES,POST_-COMMENT,DELETE_-IMAGES,UPLOAD_-IMAGES}from./types';
从“../Axios”导入Axios;
导出常量getImages=()=>{
返回调度=>{
返回Axios.get('/images/uploads')。然后(响应=>{
const data=response.data;
派遣({
类型:获取图像,
数据
});
});
};
};
imageActions.test.js
从“React”导入React;
从“酶”导入{shall,mount};
从“redux模拟存储”导入configureMockStore;
从“redux thunk”导入thunk;
从“/imageActions”导入{getImages};
从“./types”导入{GET_IMAGES};
const middleware=[thunk];
const mockStore=configureMockStore(中间件);
description('should getImages from action function',()=>{
它('should getImages from action function',()=>{
预期常数={
类型:获取图像,
数据:{}
};
const-actual=getImages();
预期(实际)。toEqual(预期);
});
});
既然您正在使用,您应该看看如何测试异步操作
您还必须模拟通过Axios
模块执行的ajax请求。例如,我将使用jest模拟Axios
模块
代码如下所示:
import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { getImages } from './imageActions';
import { GET_IMAGES } from './types';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
// Mocking the Axios get method so that it returns something in data
jest.mock('../Axios', () => ({
get: jest.fn(() => Promise.resolve({ data: ['image1', 'image2'] }))
}));
describe('should getImages from action function ', () => {
it('should getImages from action function', () => {
const expected = {
type: GET_IMAGES,
data: ['image1', 'image2']
};
// Initialize mockstore with empty state
const store = mockStore({});
// Return the promise returned by store.dispatch so that the test waits until it's resolved.
return store.dispatch(getImages()).then(() => {
// Get the actions that have been dispatched
const actions = store.getActions();
// Check that the only action has the expected values.
expect(actions[0]).toEqual(expected);
});
});
});
-你会嘲笑axios的电话吗?否则,测试将进行真正的调用,可能会失败,并且永远无法正确解决axios承诺。2.
getImages
正在返回一个函数,该函数返回另一个函数,该函数在内部进行axios调用,因此您需要做的是在测试中getImages()(dispatch)
,您可以将dispatch
作为模拟函数传递,或者发送mockedStore的调度(我不知道这是在做什么).你将如何编写此测试Miguel?你可以在这里查看@randal的示例