如何使用Jest在React中对开关案例进行单元测试? [英] How to unit test switch case in React using Jest?
本文介绍了如何使用Jest在React中对开关案例进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为此计算创建一个单元测试.我将在其他组件中使用此sum函数来计算来自API的值.在这种情况下,猫和狗将成为获取的数据.
I want to create a unit test for this calculation. I will use this sum function in my other component to calculate values coming from the API. Cats and dogs in that case will be the fetched data.
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;
}
};
推荐答案
此功能类似于您的功能:
this a function like yours :
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 });
});
});
这篇关于如何使用Jest在React中对开关案例进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文