JasmineJS教程

JasmineJS 相等检查

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 Method

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,  
}; 
在第二个期望块中,我们正在检查 currentVal 的值是否等于 5,因为 currentVal 的值为零,因此我们的测试通过并为我们提供了绿色输出。 > notEquals Method

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:"tutorialspoint", 
   name1:tutorialspoint  
};
我们将稍微修改我们的 expectexam JavaScript 文件。我们添加了两个新变量, namename1。请找出这两个添加的变量之间的区别-一个是字符串类型,另一个不是字符串类型。
以下屏幕截图是我们的测试结果,其中红色叉表示这两个值不相等,而预期相等。因此我们的测试失败了。
expectExam Error
让我们将变量 namename1 作为字符串类型变量,然后再次运行相同的 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 Method
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4