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

时间:2020-06-13 20:33:41

标签: reactjs testing jestjs switch-statement

我想为此计算创建一个单元测试。我将在其他组件中使用此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;
    }
};

2 个答案:

答案 0 :(得分:1)

此功能类似于您的功能:

  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 });
  });
});

答案 1 :(得分:1)

switch 语句可能有多种情况,我找到了一种使用 Jest test.each 方法使用不同数据测试不同情况的更简洁的方法:

util.js

export const calculate = ({ num1, num2, type }) => {
  switch (type) {
    case 'cats':
      return num1 + num2;
    case 'dogs':
      return num1 * num2;
    default:
      return 0;
  }
};

util.spec.js

describe('calculate', () => {
  test.each`
    num1 | num2 | type      | expected
    ${5} | ${5} | ${'cats'} | ${10}
    ${5} | ${5} | ${'dogs'} | ${25}
    ${5} | ${5} | ${'fish'} | ${0}
  `('returns $expected when type=$type for $num1 & $num2', ({ num1, num2, type, expected }) => {
    expect(calculate({ num1, num2, type })).toEqual(expected);
  });
});

输出

calculate
  ✓ returns 10 when type=cats for 5 & 5 (1 ms)
  ✓ returns 25 when type=dogs for 5 & 5
  ✓ returns 0 when type=fish for 5 & 5