我想为此计算创建一个单元测试。我将在其他组件中使用此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;
}
};
此功能类似于您的功能:
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 });
});
});