目录

Jasmine JS - Matchers( Matchers)

Jasmine是一个测试框架,因此它总是旨在将JavaScript文件或函数的结果与预期结果进行比较。 Matcher在Jasmine框架中的工作方式类似。

Matchers是JavaScript函数,它在实际输出和预期输出之间进行布尔比较。 有两种类型的匹配器Inbuilt matcherCustom matchers

内置匹配器

内置于Jasmine框架中的inbuilt matcher称为inbuilt matcher 。 用户可以轻松地implicitly使用它。

以下示例显示了Inbuilt Matcher如何在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()匹配器的参数进行toEqual()

自定义匹配器

内置的Jasmine系统库中没有的匹配器称为custom matcher 。 需要explicitly()定义自定义匹配器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
↑回到顶部↑
WIKI教程 @2018