JasmineJS教程

JasmineJS spy

Jasmine spy 是另一个功能,其功能与其名称指定的完全相同。它将允许您监视应用程序函数调用。 Jasmine 有两种类型的间谍技术可用。第一种方法可以通过使用 spyOn() 来实现,第二种方法可以使用 createSpy() 来实现。在本章中,我们将详细了解这两种方法。

spyOn()

spyOn() 内置在 Jasmine 库中,它允许您窥探一段确定的代码。让我们创建一个新的规范文件"spyJasmineSpec.js"和另一个名为"spyJasmine.js"的 js文件。以下是这两个文件的入口。

SpyJasmine.js

var Person = function() {}; 
Person.prototype.sayHelloWorld = function(dict) { 
   return dict.hello() + " " + dict.world(); 
}; 
var Dictionary = function() {}; 
Dictionary.prototype.hello = function() { 
   return "hello"; 
}; 
Dictionary.prototype.world = function() { 
   return "world"; 
}; 

SpyJasmineSpec.js

describe("Example Of jasmine Spy using spyOn()", function() { 
  
   it('uses the dictionary to say "hello world"', function() { 
      var dictionary = new Dictionary; 
      var person = new Person; 
    
      spyOn(dictionary, "hello");  // replace hello function with a spy 
      spyOn(dictionary, "world");  // replace world function with another spy 
    
      person.sayHelloWorld(dictionary);
      expect(dictionary.hello).toHaveBeenCalled();  
      // not possible without first spy 
  
      expect(dictionary.world).toHaveBeenCalled();  
      // not possible withoutsecond spy 
   }); 
});
在上面的代码中,我们希望 person 对象说"Hello world",但我们也希望 person 对象应该与字典对象协商,以给我们输出文字"Hello world"。
查看 Spec 文件,您可以看到我们使用了 spyOn() 函数,它实际上模仿了 helloworld 函数的功能。因此,我们实际上并不是在调用函数,而是在模仿函数调用。这就是间谍的专长。上面这段代码将产生以下输出。
spyOn 方法

createSpy()

另一种获取间谍功能的方法是使用 createSpy()。让我们使用以下代码修改我们的两个 js 文件。

SpyJasmine.js

var Person = function() {};    
Person.prototype.sayHelloWorld = function(dict) { 
   return dict.hello() + " " + dict.world(); 
}; 
var Dictionary = function() {}; 
Dictionary.prototype.hello = function() { 
   return "hello"; 
}; 
Dictionary.prototype.world = function() { 
   return "world"; 
}; 

SpyJasmineSpec.js

describe("Example Of jasmine Spy using Create Spy", function() { 
   
   it("can have a spy function", function() { 
      var person = new Person(); 
      person.getName11 = jasmine.createSpy("Name spy"); 
      person.getName11(); 
      expect(person.getName11).toHaveBeenCalled(); 
   }); 
}); 
看看规范文件,我们正在调用 Person 对象的 getName11()。尽管此函数不存在于 spy Jasmine.js 中的 person 对象中,但我们没有收到任何错误,因此输出是绿色且正面的。在这个例子中,createSpy() 方法实际上模仿了 getName11() 的功能。
以上代码将生成以下输出。
CreateSpy
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4