簡體   English   中英

用Jest測試功能和內部if循環

[英]Testing function and inner if loops with Jest

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM