目录

JasmineJS - Spies

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

spyOn()

spyOn()内置于Jasmine库中,允许您监视一段确定的代码。 让我们创建一个新的spec文件“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(); 
   }); 
}); 

看一下spec文件,我们调用Person对象的getName11() 。 虽然spy Jasmine.js中的person对象中不存在此函数,但我们没有收到任何错误,因此输出为绿色且为正。 在此示例中,createSpy()方法实际上模仿了getName11()的功能。

上面的代码将生成以下输出。

CreateSpy
↑回到顶部↑
WIKI教程 @2018