javascript - 用 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."
});
});
});
推荐阅读
- python - databricks 秘密范围“错误请求”
- r - 如何将 R 工作字典设置为远程服务器?
- intellij-idea - 无法在 Intellij 上创建 Groove 脚本 - @NotNull 参数的参数
- javascript - 将样式附加到 iFrame #document 元素
- c# - 在.net中同时运行现有应用程序和升级应用程序的方法是什么
- .htaccess - mod_expires (.htaccess) 仅适用于字体,不适用于其他文件类型
- css - 如何使用 css 缓解下拉菜单?
- python - 问题“ driver.find_element_by_xpath("//div[@class='example']"
- r - 使用长格式的 r 模拟数据
- discord - 如何将用户对象转换为名称