Jasmine SpyOn不止一次使用同样的方法 [英] Jasmine SpyOn same method more than once

查看:198
本文介绍了Jasmine SpyOn不止一次使用同样的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角度控制器,其方法可以调用 $ 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} c>。

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.

推荐答案

你可以采用不同的方式。如果你有时间在测试用例期间更改间谍实现,你可以这样做:

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

如果调用是由代码中的方法触发的,并且您无法更改间隙中的间谍实现,然后您可以创建一个接受参数并适当响应的函数:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆