Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 茉莉花间谍同样的方法不止一次_Angularjs_Unit Testing_Jasmine - Fatal编程技术网

Angularjs 茉莉花间谍同样的方法不止一次

Angularjs 茉莉花间谍同样的方法不止一次,angularjs,unit-testing,jasmine,Angularjs,Unit Testing,Jasmine,我有一个角度控制器,其方法调用两次$location.search() 第一次只需$location.search()返回值。 第二次是$location.search(“foo”,null)将其清除 我的单元测试中有以下间谍: spyOn($location,“search”).and.returnValue({foo:bar}) 即使我的实现执行了$location.search(“foo”,null),spy也会返回{foo:bar} 我需要一种方法,根据参数,为同一个方法设置两个不同的间

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

第一次只需
$location.search()
返回值。
第二次是
$location.search(“foo”,null)
将其清除

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

即使我的实现执行了
$location.search(“foo”,null)
,spy也会返回
{foo:bar}

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

我需要这个期望:
expect($location.search().foo).toEqual(null)

在单元测试结束时通过。

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

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

searchSpy.and.returnValue(null);
// do stuff
searchSpy.and.returnValue({ foo: "bar" });
// do other stuff
如果调用是由代码中的方法触发的,并且您不能在其间更改spy实现,那么您可以创建一个函数,该函数接受参数并适当响应:

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

当然,您可能会对callFake实现中的逻辑发疯,但请注意,我认为在这种情况下,可能是代码的味道。不管怎样,编码快乐

还可以直接调用模拟对象上的spy属性。代码可能如下所示:

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
对于typescript,它可能看起来像:

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
spyOn($location,'search');
($location.search).和.returnValue(null);
//做事
($location.search).and.returnValue({foo:bar})
//做其他事情

发布此答案,因为它看起来更干净,不需要额外变量。

至少对于
spyOnProperty
来说,似乎不可能多次使用
returnValue