【发布时间】:2016-07-07 17:52:41
【问题描述】:
我有一个角度服务。在这个服务中,我有一个带有函数的对象,它引用了服务上的另一个函数。 (代码如下)
我想使用 Jasmine (1.3) 来监视我的服务函数,以验证当对象的函数被调用时,它实际上调用了真正的函数。
我的问题:调用spyOn后,真正的函数还在被调用。
FooService.js
angular.module('foo').service("FooService", function() {
var self = this;
this.fooFunction = function() {
console.log("Foo function is being called");
}
this.bar = {
barFunction : self.fooFunction
}
});
FooService-spec.js
describe("Testing FooService", function() {
var service;
beforeEach(inject(function(_FooService_) {
service = _FooService_;
}));
describe("Test bar object", function() {
it("should call fooFunction when bar.barFunction is called", function() {
spyOn(service, "fooFunction");
service.bar.barFunction();
expect(service.fooFunction).toHaveBeenCalled();
});
});
});
我发现如果我将 FooServce.js 更改为以下内容,这一切正常:
FooService - 工作
angular.module('foo').service("FooService", function() {
var self = this;
this.fooFunction = function() {
console.log("Real function is being called");
}
this.bar = {
barFunction : function() {
return self.fooFunction();
}
}
});
在第一个示例中,我未能理解 JavaScript / Angular / Jasmine 的哪一部分?
【问题讨论】:
标签: javascript angularjs unit-testing jasmine spy