假设我们有一个异步 Action Creator,它会调用 API 并返回一个包含数据的 Action 对象。我们使用 umi 框架,Redux 和 Redux Thunk 来管理状态和异步操作。现在,我们想要编写一个测试用例来模拟异步 dispatch。

首先,我们需要安装 Jest:

npm install --save-dev jest

然后,我们需要编写我们的测试用例。我们将使用 Jest 提供的 mockspy 功能来模拟异步操作和检查 dispatch 的行为。以下是测试用例的代码:

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { fetchUserData } from '@/services/user';
import { FETCH_USER_DATA_SUCCESS, FETCH_USER_DATA_FAILURE } from '@/constants/user';
import { fetchUserDataAction } from '@/actions/user';

const mockStore = configureMockStore([thunk]);

describe('fetchUserDataAction', () => {
  it('should dispatch FETCH_USER_DATA_SUCCESS when fetchUserData is successful', async () => {
    fetchUserData.mockResolvedValueOnce({ data: { name: 'John Doe' } });

    const expectedActions = [{ type: FETCH_USER_DATA_SUCCESS, payload: { name: 'John Doe' } }];

    const store = mockStore({});

    await store.dispatch(fetchUserDataAction());

    expect(store.getActions()).toEqual(expectedActions);
  });

  it('should dispatch FETCH_USER_DATA_FAILURE when fetchUserData fails', async () => {
    fetchUserData.mockRejectedValueOnce(new Error('API Error'));

    const expectedActions = [{ type: FETCH_USER_DATA_FAILURE, payload: 'API Error' }];

    const store = mockStore({});

    await store.dispatch(fetchUserDataAction());

    expect(store.getActions()).toEqual(expectedActions);
  });
});

在上面的代码中,我们首先导入了 configureMockStorethunk,以及我们要测试的异步 Action Creator 和相关常量和辅助函数。

然后,我们使用 mockResolvedValueOncemockRejectedValueOnce 分别模拟了成功和失败的 API 调用。我们还定义了期望的 Action 对象数组。

接下来,我们创建了一个 mock store,并使用 await 关键字调用了异步 Action Creator。最后,我们使用 expect 函数来检查 dispatch

umi框架下使用 jest编写一个模拟异步dispatch的测试用例

原文地址: https://www.cveoy.top/t/topic/fvB0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录