[英]Testing function and inner if loops with Jest
I need help on approach and how do I implement test on javascript function and that has if loops inside. 我需要有关方法的帮助以及如何在javascript函数上执行测试,并且其中包含if循环。
My code is like below : 我的代码如下:
function calculate(obj, buttonName) {
//When AC button is pressed, we will be displaying 0 on screen, so all states go to null.
if (buttonName === "AC") {
return {
result: null,
nextOperand: null,
operator: null
};
}
if (buttonName === ".") {
if (obj.nextOperand) {
//cant have more than one decimal point in a number, dont change anything
if (obj.nextOperand.includes(".")) {
return {};
}
//else append dot to the number.
return { nextOperand: obj.nextOperand + "." };
}
//If the operand is pressed that directly starts with .
return { nextOperand: "0." };
}
}
How do I write a test case for above with Jest 我如何用Jest编写上面的测试用例
You could just run through all the cases like so: 您可以像这样处理所有情况:
describe('calculate', () => {
it('should return object with result, nextOperand, and operator as null if buttonName is "AC"', () => {
expect(calculate({}, "AC")).toEqual({
result: null,
nextOperand: null,
operator: null
});
});
it('should return empty object if buttonName is "." and object nextOperand contains a "."', () => {
expect(calculate({ nextOperand: ".5" }, ".")).toEqual({});
});
it('should return object with nextOperand appended with a "." if buttonName is "." and object nextOperand does not contain a "."', () => {
expect(calculate({ nextOperand: "60" }, ".")).toEqual({
nextOperand: "60."
});
});
it('should return object with nextOperand as 0." with a "." if buttonName is "." and object nextOperand does not exist', () => {
expect(calculate({}, ".")).toEqual({
nextOperand: "0."
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.