Jasmine SpyOn 不止一次使用相同的方法 [英] Jasmine SpyOn same method more than once
问题描述
我有一个角度控制器,它的方法调用 $location.search()
两次.
I have an angular controller with a method that calls $location.search()
twice.
第一次只是 $location.search()
返回值.
第二次是 $location.search("foo", null)
清除它.
First time is just $location.search()
to return the value.
Second time is $location.search("foo", null)
to clear it.
我的单元测试中有以下间谍:spyOn($location, "search").and.returnValue({ foo: "bar" });
I have the following spy in my unit test:
spyOn($location, "search").and.returnValue({ foo: "bar" });
即使我的实现执行 $location.search("foo", null)
,间谍似乎也会返回 {foo:"bar"}
.
It appears the spy returns {foo:"bar"}
even when my implementation does $location.search("foo", null)
.
我需要一种方法,根据参数为同一方法设置两个不同的间谍.
I need a way to have two different spies for the same method depending on the arguments.
我需要这个期望:expect($location.search().foo).toEqual(null);
在单元测试结束时通过.
I need this expect:
expect($location.search().foo).toEqual(null);
to pass at the end of the unit test.
推荐答案
你可以用不同的方式去做.如果您有时间在测试用例期间更改 spy 实现,您可以这样做:
You can go about it different ways. If you have time to change the spy implementation during your testcase, you can do this:
var searchSpy = spyOn($location,'search');
searchSpy.and.returnValue(null);
// do stuff
searchSpy.and.returnValue({ foo: "bar" });
// do other stuff
如果调用是由代码中的某个方法触发的,并且您无法更改其间的 spy 实现,那么您可以创建一个接受参数并做出适当响应的函数:
If the calls are triggered by a method in your code, and you cannot change the spy implementation in between, then you can create a function that takes the arguments and responds appropriately:
spyOn($location,'search').and.callFake(function(someParam){
if (someParam) {
return { foo: "bar" };
} else {
return { foo: null };
}
});
当然,您可以在 callFake 实现中对逻辑发疯,但请注意,我认为在这种情况下,它可能是代码异味.无论如何,快乐的编码!
Of course you can go crazy with logic in your callFake implementation, but beware, I think in that case it might be a code smell. Anyway, happy coding!
这篇关于Jasmine SpyOn 不止一次使用相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!