JasmineJS - Spies
Jasmine Spies是另一个功能,其功能与名称完全相同。它允许您监视应用程序函数调用。Jasmine 中有两种类型的Spies技术。第一种方法可以使用 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() 函数,它实际上模仿了 hello 和 world 函数的功能。因此,我们实际上不是在调用该函数,而是在模仿函数调用。这是 Spies 的专长。上面的代码将产生以下输出。
createSpy()
获取Spies功能的另一种方法是使用 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() 的功能。
上述代码将生成以下输出。