使用Jest测试函数和内部if循环
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Jest测试函数和内部if循环相关的知识,希望对你有一定的参考价值。
我需要有关方法的帮助,如何在javascript函数上实现测试,并且内部有if循环。
我的代码如下:
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." };
}
}
如何用Jest编写上面的测试用例
答案
您可以像这样运行所有情况:
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."
});
});
});
以上是关于使用Jest测试函数和内部if循环的主要内容,如果未能解决你的问题,请参考以下文章
如何在构造函数内部使用上下文的情况下使用 jest 和酶来测试反应上下文?
jest中的mock,jest.fn()jest.spyOn()jest.mock()
jest中的mock,jest.fn()jest.spyOn()jest.mock()