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

Redux reducer单元测试未通过,请求技术排查指导

Redux Reducer单元测试失败求助

本人刚接触单元测试,尤其不熟悉Redux测试,恳请谅解基础问题。我尝试测试一个简单的Redux reducer,但始终无法通过。

Reducer代码

import { ActionTypes } from "../constants/action-types";

const initialState = {
  products: [],
};

export const productReducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case ActionTypes.FETCH_PRODUCTS:
      return { ...state, products: payload };
    case ActionTypes.RESET_PRODUCTS:
      return {};
    default:
      return state;
  }
};

测试代码

import { ActionTypes } from "../../redux/constants/action-types";
import { productReducer } from ".././../redux/reducers/productReducer";

describe("Product reducer", () => {
  describe("fetching products", () => {
    it("adds products", () => {
      const action = {
        type: ActionTypes.FETCH_PRODUCTS,
        product: [{ name: "test" }],
      };

      const initialState = undefined;
      const nextState = productReducer(initialState, action);

      expect(nextState).toEqual([{ name: "test" }]);
    });
  });
});

报错信息

expect(received).toEqual(expected) // deep equality

Expected: [{"name": "test"}]
Received: {"products": undefined}

我完全不清楚该如何正确测试这个reducer,希望得到帮助。


问题分析与修复

你的测试存在两个关键错误:

  • Action属性名不匹配:reducer中通过payload接收数据,但你定义的action里用的是product,导致reducer无法获取到有效数据,最终products字段为undefined。
  • 断言预期值结构错误:reducer返回的是包含products属性的对象,而你直接断言成了数组,与实际返回的状态结构不符。

修复后的测试代码如下:

import { ActionTypes } from "../../redux/constants/action-types";
import { productReducer } from ".././../redux/reducers/productReducer";

describe("Product reducer", () => {
  describe("fetching products", () => {
    it("adds products", () => {
      const testProducts = [{ name: "test" }];
      const action = {
        type: ActionTypes.FETCH_PRODUCTS,
        payload: testProducts, // 修正为payload
      };

      const initialState = undefined;
      const nextState = productReducer(initialState, action);

      expect(nextState).toEqual({ products: testProducts }); // 断言正确的对象结构
    });
  });
});

额外建议:当前RESET_PRODUCTS分支返回的是{},如果需要重置回初始状态,建议改成return initialState,逻辑会更合理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:45:41