JasmineJS - 布林值檢查



除了相等性檢查以外,Jasmine 還提供了一些檢查布林條件的方法。以下是幫助我們檢查布林條件的方法。

ToBeTruthy()

此布林匹配器用於在 Jasmine 中檢查結果是否等於 true 或 false。

以下示例將幫助我們瞭解 toBeTruthy() 函式的工作原理。

ExpectSpec.js

describe("Different Methods of Expect Block",function () {
   it("The Example of toBeTruthy() method",function () {   
      expect(expectexam.exampleoftrueFalse(5)).toBeTruthy();    
   });
}); 

Expectexam.js

window.expectexam = {  
   exampleoftrueFalse: function (num) {  
      if(num < 10)    
         return true;  
      else   
         return false;  
   },  
};

當我們傳遞數字 5,小於 10 時,此測試用例將透過併為我們提供以下輸出。

toBeTruthy Method

如果我們傳遞一個大於 10 的數字,那麼這個綠色的測試將變為紅色。在第二個螢幕截圖中,你可以看到,在傳遞一個大於 10 的值後,預期的測試用例失敗並生成紅色的輸出,指出“預期 false 為 truthy”。

toBeTruthy Error

toBeFalsy()

toBeFalsy() 的工作方式也與 toBeTruthy() 方法一樣。它匹配預期輸出為 false,而 toBeTruthy 則匹配預期輸出為 true。以下示例將幫助你瞭解 toBeFalsy() 的基本工作原理。

ExpectSpec.js

describe("Different Methods of Expect Block",function() { 
   it("The Example of toBeTruthy() method",function () {
      expect(expectexam.exampleoftrueFalse(15)).toBeFalsy();   
   });
});

Expectexam.js

window.expectexam = {  
   exampleoftrueFalse: function (num) {  
      if(num < 10)    
         Return true;  
      else   
         return false; 
   },
}; 

上面的程式碼將透過 Jasmine 測試用例,因為我們傳遞的值大於 10,並且預期輸出為 false。因此,瀏覽器會向我們顯示一個綠色標記,表示已透過。

toBeTruthy Method
廣告