单元测试多个调用具有不同参数angularjs / jasmine的相同函数

时间:2018-04-30 15:30:17

标签: angularjs jasmine jasmine2.0

我正在尝试测试类似的代码。

它的作用是当我得到409时它改变了参数并再次调用相同的函数。



function testSomething(stuff) {
  console.log(stuff);
  return customService.doSomething().then(function() {
    return customService.doSomethingElse().then(function(something) {
      //do something here
      return $q.resolve(something);
    });
  }, function(error) {
    if(error.status === 409) {
      //change stuff
      //something like stuff = newStuff;
      testSomething(stuff);
    }
  });
}




所以我试图在第一次和第二次调用时检查函数参数。但是当第二次调用的参数显示未定义时。断言toHaveBeenCallTimes 2也失败了。



it('should handle 409', function() {
  spyOn(customService, 'doSomething').and.returnValue($q.reject({
    status: 409
  }));
  spyOn(someService, 'testSomething').and.callThrough();
  
  someService.testSomething(stuff);
  $scope.$apply();

  expect(someService.testSomething.calls.argsFor[0]).toEqual([stuff]);
  expect(customService.doSomething).toHaveBeenCalled();
  expect(someService.testSomething.calls.argsFor[1]).toEqual([newStuff]);
  expect(someService.testSomething).toHaveBeenCalledTimes(2);
});




虽然我可以在控制台中看到console.log(stuff)在正确的参数中记录2次。

1 个答案:

答案 0 :(得分:0)

我猜你的间谍只是互相覆盖。你可以这样做:

spyOn(customService, 'doSomething').and.returnValue($q.reject({
    status: 409
  }));
  someService.testSomething(stuff);
  // now doSomething is called and $q.reject is retuend
  expect(someService.testSomething.calls.argsFor[0]).toEqual([stuff]);      

  spyOn(customService, 'doSomething').and.returnValue($q.when());
  $scope.$apply();

或者像这样,我更喜欢这个:

var index = 0;

spyOn(customService, 'doSomething').and.callFake(() => {
  index++;
  return index === 1 ? $q.reject({status: 409}) : $q.when();
});