You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求协助编写Redux异步action fetchP2pPriceConstraints的测试用例

Redux异步Action测试用例实现

下面是针对你提供的fetchP2pPriceConstraints异步Action的完整测试用例,使用Jest + redux-mock-store + redux-thunk实现,覆盖所有核心场景:

准备依赖

确保你的项目已安装以下依赖:

npm install --save-dev jest redux-mock-store redux-thunk

测试代码实现

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { fetchP2pPriceConstraints, PRICE_CONSTRAINTS } from './path-to-your-action-file';
import api from './path-to-your-api-file';

// 配置Mock Store,注入thunk中间件
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('fetchP2pPriceConstraints Action Tests', () => {
  // 每次测试前重置API Mock
  beforeEach(() => {
    jest.spyOn(api, 'fetchP2pConstraints').mockClear();
  });

  // 场景1:接口请求成功,状态码与业务码均为200
  it('dispatches PRICE_CONSTRAINTS action on successful request', async () => {
    // Mock API成功响应
    const mockSuccessResponse = {
      status: 200,
      data: Promise.resolve({
        code: 200,
        result: { minPrice: 10, maxPrice: 100 }
      })
    };
    api.fetchP2pConstraints.mockResolvedValue(mockSuccessResponse);

    // 预期的Action
    const expectedActions = [
      {
        type: PRICE_CONSTRAINTS,
        payload: {
          priceConstraints: { minPrice: 10, maxPrice: 100 }
        }
      }
    ];

    const store = mockStore({});
    await store.dispatch(fetchP2pPriceConstraints());

    // 验证Action是否正确dispatch
    expect(store.getActions()).toEqual(expectedActions);
    // 验证API方法是否被调用一次
    expect(api.fetchP2pConstraints).toHaveBeenCalledTimes(1);
  });

  // 场景2:接口返回非200状态码
  it('rejects with response when API status is not 200', async () => {
    const mockErrorResponse = {
      status: 404,
      data: Promise.resolve({ code: 404, message: 'Resource Not Found' })
    };
    api.fetchP2pConstraints.mockResolvedValue(mockErrorResponse);

    const store = mockStore({});
    // 验证Promise被reject且返回的响应正确
    await expect(store.dispatch(fetchP2pPriceConstraints())).rejects.toEqual(mockErrorResponse);
    // 验证没有dispatch任何Action
    expect(store.getActions()).toEqual([]);
  });

  // 场景3:接口状态码200但业务码非200
  it('rejects with response when business code is not 200', async () => {
    const mockFailedResponse = {
      status: 200,
      data: Promise.resolve({ code: 500, message: 'Internal Server Error' })
    };
    api.fetchP2pConstraints.mockResolvedValue(mockFailedResponse);

    const store = mockStore({});
    await expect(store.dispatch(fetchP2pPriceConstraints())).rejects.toEqual(mockFailedResponse);
    expect(store.getActions()).toEqual([]);
  });
});

关键说明

  • 使用jest.spyOnMock API方法,避免触发真实网络请求
  • redux-mock-store模拟Redux Store,方便跟踪dispatch的Action
  • 所有异步测试使用async/await确保测试等待异步操作完成
  • 每个测试前清除Mock,避免测试用例间的相互影响

内容的提问来源于stack exchange,提问作者Hasnain Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:05:21