单元测试 react redux thunk dispatches with jest and react testing library for "v: 16.13.1",
Posted
技术标签:
【中文标题】单元测试 react redux thunk dispatches with jest and react testing library for "v: 16.13.1",【英文标题】:Unit testing react redux thunk dispatches with jest and react testing library for "v: 16.13.1", 【发布时间】:2021-09-13 01:17:07 【问题描述】:我有以下功能。
常量 loadUsers= () => 返回异步(调度)=> 调度(用户请求()); 让响应=空 尝试 响应=等待 UserService.getUser(); 调度(用户加载()); 捕捉(错误) 调度(用户错误(错误)); 最后 调度(用户成功(响应)); ; ;通过以下单元测试,我可以点击“dispatch(userRequest());”
描述('用户重击',()=> it('发送用户请求', async () => 常量调度 = jest.fn(); 等待加载用户()(调度); 期望(调度).toHaveBeenCalledWith(用户请求()); ); );但是我不知道如何测试线及以下response= await UserService.getUser();
。尽管该函数并不复杂,而且我编写复杂的测试没有多大价值,但我需要它来构建我的管道。
任何帮助将不胜感激。
提前致谢。
更新->用户服务
从'axios'导入axios; const USERS_ENDPOINT = '/用户'; 导出 const getUser= async () => 常量响应 = 等待 axios.get(PRODUCTS_ENDPOINT, ); 返回响应。数据; ; 导出默认getUser;
【问题讨论】:
UserService
来自哪里?显示代码
@slideshowp2 使用 UserSerivce 更新
【参考方案1】:
经过几天的研究,我最终通过以下方式测试了逻辑。
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import * as reactRedux from 'react-redux';
import axios from 'axios';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('load user thunk', () =>
it('dispatches load user and error on call when API is not mocked', async () =>
const store = mockStore();
const requestDispatch= userRequest();
const errorDispatch= userError("Mock Message");
await store.dispatch(await loadUsers());
const actionsResulted = store.getActions();
const expectedActions = [
requestDispatch,
errorDispatch,
];
expect(actionsResulted.length).toEqual(expectedActions.length);
expect(actionsResulted[0].type).toEqual(expectedActions[0].type);
expect(actionsResulted[1].type).toEqual(expectedActions[1].type);
);
it('dispatches load user and success on call when API is mocked', async () =>
const store = mockStore();
const requestDispatch= userRequest();
const successDispatch= userSuccess("Mock Data");
jest
.spyOn(axios, 'get')
.mockResolvedValue( status: 200, data: "Mock Data");
await store.dispatch(await loadUsers());
const actionsResulted = store.getActions();
const expectedActions = [
requestDispatch,
successDispatch,
];
expect(actionsResulted.length).toEqual(expectedActions.length);
expect(actionsResulted[0].type).toEqual(expectedActions[0].type);
expect(actionsResulted[1].type).toEqual(expectedActions[1].type);
);
【讨论】:
以上是关于单元测试 react redux thunk dispatches with jest and react testing library for "v: 16.13.1",的主要内容,如果未能解决你的问题,请参考以下文章
使用 Redux Thunk 测试 AsyncStorage
React 上下文 API 和/或 React-Redux-Thunk
React + redux + axios + thunk,等待interceptors.response 刷新token