- JasmineJS 教程
- JasmineJS - 主页
- JasmineJS - 概述
- JasmineJS - 环境设置
- JasmineJS - 编写文本和执行
- JasmineJS - BDD 架构
- JasmineJS - 测试构建块
- JasmineJS - 匹配器
- JasmineJS - 跳过块
- JasmineJS - 平等检查
- JasmineJS - 布尔检查
- JasmineJS - 顺序检查
- JasmineJS - 空检查
- JasmineJS - 不平等检查
- JasmineJS - 不是数字检查
- JasmineJS - 异常检查
- JasmineJS - beforeEach()
- JasmineJS - afterEach()
- JasmineJS - 间谍
- JasmineJS 有用资源
- JasmineJS - 快速指南
- JasmineJS - 有用的资源
- JasmineJS - 讨论
JasmineJS - 间谍
Jasmine间谍是另一个功能,其功能与其名称完全相同。它将允许您监视您的应用程序函数调用。Jasmine 中有两种类型的间谍技术。第一种方法可以使用spyOn()来实现,第二种方法可以使用createSpy()来实现。在本章中,我们将更多地了解这两种方法。
暗中监视()
间谍On()内置于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() 函数,它实际上模仿了hello和world函数的功能。因此,我们实际上并不是在调用函数,而是模仿函数调用。这就是间谍的专长。上面的代码将产生以下输出。
创建间谍()
获取间谍功能的另一种方法是使用 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()。尽管该函数不存在于间谍 Jasmine.js 的person 对象中,但我们没有收到任何错误,因此输出为绿色且为正值。在此示例中,createSpy() 方法实际上模仿了 getName11() 的功能。
上面的代码将生成以下输出。
