Jasmine SpyOn不止一次使用同样的方法

时间:2016-03-24 12:44:28

标签: angularjs unit-testing jasmine

我有一个角度控制器,其方法可以调用$location.search()两次。

第一次只是$location.search()才能返回值 第二次$location.search("foo", null)清除它。

我的单元测试中有以下间谍:
spyOn($location, "search").and.returnValue({ foo: "bar" });

即使我的实施{foo:"bar"} {。}},间谍似乎也会返回$location.search("foo", null)

我需要一种方法,根据参数为同一方法设置两个不同的间谍。

我需要这个期望:
expect($location.search().foo).toEqual(null);
在单元测试结束时通过。

2 个答案:

答案 0 :(得分:7)

你可以采取不同的方式。如果您有时间在测试用例期间更改间谍实现,则可以执行以下操作:

var searchSpy = spyOn($location,'search');

searchSpy.and.returnValue(null);
// do stuff
searchSpy.and.returnValue({ foo: "bar" });
// do other stuff

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

spyOn($location,'search').and.callFake(function(someParam){
  if (someParam) { 
      return { foo: "bar" };
  } else {
      return { foo: null };
  }
});

当然你可以在callFake实现中疯狂地使用逻辑,但要注意,我认为在这种情况下它可能是代码味道。无论如何,快乐的编码!

答案 1 :(得分:0)

还可以直接在模拟对象上调用间谍属性。该代码可能类似于:

spyOn($location,'search');

$location.search.and.returnValue(null);
// do stuff
$location.search.and.returnValue({ foo: "bar" })
// do other stuff

对于打字稿,它可能看起来像:

spyOn($location,'search');

(<jasmine.Spy>$location.search).and.returnValue(null);
// do stuff
(<jasmine.Spy>$location.search).and.returnValue({ foo: "bar" })
// do other stuff

发布此答案,因为它看起来更干净并且不需要其他变量。