【问题标题】:Jasmine SpyOn same method more than onceJasmine SpyOn 不止一次使用相同的方法
【发布时间】:2016-07-12 01:32:01
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    你可以用不同的方式去做。如果您有时间在测试用例期间更改 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 实现中对逻辑发疯,但请注意,我认为在这种情况下,它可能是代码异味。不管怎样,编码愉快!

    【讨论】:

    • 至少对于spyOnProperty,似乎不可能多次使用returnValue。
    【解决方案2】:

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

    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
    

    发布此答案是因为它可能看起来更简洁,并且不需要额外的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-18
      • 2020-10-08
      • 2015-08-22
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      相关资源
      最近更新 更多