JasmineJS教程

JasmineJS 匹配器

Jasmine 是一个测试框架,因此它始终旨在将 JavaScript 文件或函数的结果与预期结果进行比较。 Matcher 在 Jasmine 框架中的工作方式类似。
Matchers 是在实际输出和预期输出之间进行布尔比较的 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() { 
      // 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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4