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 内置系统库中不存在的匹配器称为 自定义匹配器。自定义匹配器需要 explicitly() 定义。在下面的示例中,我们将看到自定义匹配器的工作原理。

describe('This custom matcher example', function() {
   
   beforeEach(function() { 
      // 我们应该在 beforeEach() 函数中添加自定义匹配。
      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