目录

Jasmine JS - 平等检查( Equality Check)

Jasmine提供了许多方法来帮助我们检查任何JavaScript函数和文件的相等性。 以下是检查平等条件的一些示例。

toEqual()

toEqual()是内置的Jasmine库中最简单的匹配器。 它只是匹配作为此方法的参数给出的操作的结果是否与其结果匹配。

以下示例将帮助您了解此匹配器的工作原理。 我们有两个要测试的文件,名为“expectexam.js” ,另一个我们需要测试的文件是“expectSpec.js”

Expectexam.js

window.expectexam = {    
   currentVal: 0,   
};

ExpectSpec.js

describe("Different Methods of Expect Block",function (){ 
   it("The Example of toEqual() method",function (){   
      //this will check whether the value of the variable  
      // currentVal is equal to 0 or not.  
      expect(expectexam.currentVal).toEqual(0);  
   }); 
});

成功执行后,这些代码将产生以下输出。 请记住,您需要按照前面示例中的说明将这些文件添加到specRunner.html文件的标题部分。

toEquals方法

not.toEqual()

not.toEqual()与toEqual()完全相反。 当我们需要检查值是否与任何函数的输出不匹配时,使用not.toEqual()

我们将修改上面的示例以显示其工作原理。

ExpectSpec.js

describe("Different Methods of Expect Block",function (){ 
   it("The Example of toEqual() method",function (){
      expect(expectexam.currentVal).toEqual(0);  
   });   
   it("The Example of not.toEqual() method",function (){  
      //negation  testing expect(expectexam.currentVal).not.toEqual(5); 
   }); 
});

Expectexam.js

window.expectexam = { 
   currentVal: 0,  
}; 

在第二个expect块中,我们检查currentVal的值是否等于5,因为currentVal的值为零,因此我们的测试通过并为我们提供绿色输出。

notEquals方法

toBe()

toBe()匹配器以与toEqual()类似的方式工作,但它们在技术上彼此不同。 toBe()匹配器与对象的类型匹配,而toEqual()与结果的等效性匹配。

以下示例将帮助您了解toBe()匹配器的工作原理。 这个匹配器完全等同于JavaScript的“===”运算符,而toEqual()类似于JavaScript的“==”运算符。

ExpectSpec.js

describe("Different Methods of Expect Block",function (){  
   it("The Example of toBe() method",function (){ 
      expect(expectexam.name).toBe(expectexam.name1);     
   });   
});

Expectexam.js

window.expectexam = {  
   currentVal: 0, 
   name:"iowiki", 
   name1:iowiki  
};

我们将略微修改我们的expectexam JavaScript文件。 我们添加了两个新变量, namename1 。 请找出这两个添加的变量之间的区别 - 一个是字符串类型,另一个不是字符串类型。

截图是我们的测试结果,其中红叉表示这两个值不相等,而预计它们是相等的。 因此我们的测试失败。

expectExam错误

让我们将变量namename1为String类型变量, SpecRunner.html再次运行相同的SpecRunner.html 。 现在检查输出。 它将证明toBe()不仅与变量的等价性匹配,而且还与变量的数据类型或对象类型匹配。

not.toBe()

如前所述,并非只是对toBe()方法的否定。 当预期结果与函数或JavaScript文件的实际输出匹配时,它会失败。

以下是一个简单的示例,可帮助您了解not.toBe()匹配器的工作原理。

describe("Different Methods of Expect Block",function (){ 
   it("The Example of not.toBe() method",function (){ 
      expect(true).not.toBe(false);    
   });   
});

在这里,Jasmine将尝试将true与false匹配。 由于true不能与false相同,因此该测试用例将有效并通过。

toBe方法
↑回到顶部↑
WIKI教程 @2018