JasmineJS - 間諜



Jasmine 間諜是另一個功能,它完全按照其名稱指定的功能執行。它允許您監視應用程式函式呼叫。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 物件諮詢 dictionary 物件以提供輸出文字“Hello world”。

檢視規範檔案,您可以在其中看到我們使用了 spyOn() 函式,該函式實際上模擬了helloworld函式的功能。因此,我們實際上並沒有呼叫函式,而是模擬了函式呼叫。這就是間諜的特殊之處。上面的程式碼片段將產生以下輸出。

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(); 
   }); 
}); 

檢視規範檔案,我們正在呼叫Person物件的getName11()。儘管此函式在spy Jasmine.js中的 person 物件中不存在,但我們沒有收到任何錯誤,因此輸出為綠色且為正。在此示例中,createSpy() 方法實際上模擬了 getName11() 的功能。

上面的程式碼將生成以下輸出。

CreateSpy
廣告