为什么茉莉间谍无法通过引用解析功能对象? [英] Why jasmine spy doesn't resolve the function object by reference?
问题描述
我有以下简单服务
app.factory('Shoes', function() {
function a() {return 12;}
function b() {return a();}
return {
a: a,
b: b
}
})
我想测试在调用方法 b
时是否正在调用方法 a
.我的测试如下:
I want to test if the method a
is being called when I call method b
. My test looks like this:
describe('Testing a Shoes service', function() {
var service;
beforeEach(module('plunker'));
beforeEach(inject(function(Shoes) {
service = Shoes;
}))
it('.b should call .a', function() {
spyOn(service, 'a');
service.b();
expect(service.a).toHaveBeenCalled();
})
});
但是测试失败.相关的插件在此处.我已经从这些答案中了解了如何解决问题..仍然有一个未解决的问题:
But the tests fail. Relevant plunker is here. I've already know how to resolve the problem in the plunker from those answers. Still there is one unresolved question:
为什么不解析原始功能对象?
我认为系统是这样工作的(假设间谍用附加逻辑来装饰功能)
I thought that the system works like this (assuming spyies decorate the function with additional logic)
当我调用 service.a
时没有间谍时,它被解析为:
When I have no spies when I call service.a
it's being resolved as:
A) service.a -> a()
当我创建间谍时,它会装饰功能
and when I create a spy, it decorates the function
B) spy -> service.a => service.a*()
但是 service.a
基本上是原始 a()
的引用,因此最后我们应该为已解析的函数对象设置一个间谍:
but the service.a
is basically a reference for original a()
so we should have a spy set for resolved function object in the end:
A + B => spy -> service.a -> a => a*()
推荐答案
调用 spyOn(service,'a')
后, service.a
不再是您在函数中定义的 a
-这是一个间谍函数.该间谍函数恰巧调用了 a
,但它不是 a
;它具有不同的身份,并且具有不同的功能.
After you call spyOn(service, 'a')
, service.a
is no longer the a
you defined in the function -- it is a spy function. That spy function happens to call a
, but it is not a
; it has a different identity and is a different function.
但是,设置 service
的 a
属性不会更改您在 app.factory
function a >.您只需更改 service
,以使其 a
属性不再引用原始的 a
.相比之下,您的 b
函数永远不会将其引用更改为原始的 a
.它直接从最初声明了 a
和 b
的本地 app.factory
范围获取 a
. service
用间谍替换其原始 a
的事实不会影响 b
对 a()
的调用,因为它没有引用 service.a
.
However, setting the a
property of service
does not change the function a
you declared inside app.factory
. You've simply changed service
so that its a
property no longer refers to your original a
. By contrast, your b
function never changes its reference to the original a
. It gets a
straight from the local app.factory
scope in which a
and b
were originally declared. The fact that service
replaces its original a
with a spy does not affect b
's call to a()
, because it does not refer to service.a
.
这篇关于为什么茉莉间谍无法通过引用解析功能对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!