Javascript 用Jest测试函数和内部if循环

Javascript 用Jest测试函数和内部if循环,javascript,jestjs,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,

我需要有关方法以及如何在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."
    });
  });
});