javascript - 使用 Jest 测试函数和内部 if 循环

标签 javascript jestjs

我需要有关方法的帮助以及如何实现对 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."
    });
  });
});

关于javascript - 使用 Jest 测试函数和内部 if 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55233897/

相关文章:

javascript - 如何在 Chrome 扩展程序中操作新窗口?

javascript - Jest 无法加载 svg 文件

javascript - 在javascript中对PCM音频缓冲区进行下采样

reactjs - 使用 Storyshots 渲染 React Portal 时出错

javascript - axios请求抛出未知错误

javascript - 有没有办法从 Jest 中排除文件模式?

integration-testing - Jest 集成测试 - 如何管理全局上下文?

javascript - 现代 JavaScript 引擎执行哪些优化?

javascript - 在输入字段输入/选择值时自动隐藏/显示元素(不使用 keyup() 或单击)

javascript - 使用 Hapi.js 框架的多个服务器实例