如何使用Jest在React中对开关案例进行单元测试?

问题描述 投票:0回答:1

我想为此计算创建一个单元测试。我将在其他组件中使用此sum函数来计算来自API的值。在这种情况下,猫和狗将被提取出数据。

export const sum = (value, number, type) => {
    let result;
    switch (type) {
        case 'cats':
            result = round(sumBy(slice(value, 0, number), 'cats'));
            return Number.isNaN(result) ? 0 : result;
        case 'dogs':
            result = round(sumBy(slice(value, 0, number), 'dogs'));
            return Number.isNaN(result) ? 0 : result;
        default:
            return 0;
    }
};
reactjs testing switch-statement jest
1个回答
0
投票

此功能类似于您的功能:

  const sum = (value, number, type) => {
  let result;
  switch (type) {
    case "cats":
      return { ["cats"]: value * number };
    case "dogs":
      return { ["dogs"]: value + number };
    default:
      return 0;
  }
};
module.exports = sum;

测试:

describe("sum function", () => {
  it("should return 0", () => {
    expect(sum(1, 1)).toBe(0);
  });
  it("should return cats", () => {
    expect(sum(3, 2, "cats")).toEqual({ cats: 6 });
  });
  it("should return dogs", () => {
    expect(sum(10, 5, "dogs")).toEqual({ dogs: 15 });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.