JasmineJS - 匹配器



Jasmine 是一個測試框架,故其始終旨在將 JavaScript 檔案或函式的結果與預期結果進行比較。匹配器在 Jasmine 框架中起著相似的作用。

匹配器是執行實際輸出和預期輸出之間的布林比較的 JavaScript 函式。匹配器分為兩種型別:內建匹配器自定義匹配器

內建匹配器

內建在 Jasmine 框架中的匹配器稱為內建匹配器。使用者可以輕鬆地隱式使用它。

以下示例展示了內建匹配器如何在 Jasmine 框架中工作。我們在前面的章節中已使用過一些匹配器。

describe("Adding single number ", function () {  

   //example of toEqual() matcher    
   it("should add numbers",function() { 
      expect(nested.add(5)).toEqual(5); 
      expect(nested.add(5)).toEqual(10); 
   });   
   
   it("should add numbers",function() { 
      expect(nested.addAny(1,2,3)).toEqual(6); 
   });
}

在此示例中,toEqual() 是內建匹配器,它會將 add()addAny() 方法的結果與傳遞給 toEqual() 匹配器的引數進行比較。

自定義匹配器

不在 Jasmine 內建系統庫中的匹配器稱為自定義匹配器。自定義匹配器需要顯式定義。在以下示例中,我們將瞭解自定義匹配器如何工作。

describe('This custom matcher example', function() {
   
   beforeEach(function() { 
      // We should add custom matched in beforeEach() function. 
      jasmine.addMatchers ({ 
         validateAge: function() { 
            Return {    
               compare: function(actual,expected) {
                  var result = {}; 
                  result.pass = (actual > = 13 && actual < = 19);
                  result.message = 'sorry u are not a teen ';
                  return result; 
               }   
            };   
         }    
      });    
   }); 
    
   it('Lets see whether u are teen or not', function() { 
      var myAge = 14; 
      expect(myAge).validateAge();         
   });   
    
   it('Lets see whether u are teen or not ', function() { 
      var yourAge = 18;
      expect(yourAge).validateAge();  
   });
});

在上面的示例中,validateAge() 作為匹配器工作,它實際上驗證了你的年齡與某些範圍。在此示例中,validateAge() 作為自定義匹配器。將此 JS 檔案新增到 SpecRunner.html 中並執行它。它將生成以下輸出。

ValidateAge
廣告
© . All rights reserved.