JasmineJS -Spies

Jasmine spy是另一个与其名称指定完全相同的功能.它将允许您监视您的应用程序函数调用. 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()函数,它实际上模仿了你好的功能世界功能.因此,我们实际上并没有调用函数,而是模仿函数调用.这是间谍的特长.上面的代码将产生以下输出.

spyOn Method

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