angularjs - 如何使用 Jasmine 模拟链式 promise ?

标签 angularjs jasmine angular-promise

我正在为包含这段代码的方法编写单元测试:

Name.get($scope.nameId).then(function(name){
    Return name;
}).then(doSomething);

function doSomething(name)看起来像这样。

function doSomething(name){
    addNametoList(name);
}

我不需要测试这部分代码。因为我不能在测试中忽略它(或者我可以吗?),所以我需要模拟它。我 mock 了第一个 promise

 spyOn(mockName, 'get').and.returnValues($q.resolve({"Mike"})); 

并认为它会通过第二个then(doSomething)传播但是nameundefined在功能addNametoList

我想我也必须 mock doSomething但我不知道如何将它们链接在一起。

最佳答案

您的(部分) Controller 代码

$scope.list = [];

function addNameToList(name) {
  $scope.list.push(name);
}

function doSomething(name){
  addNametoList(name);
}

$scope.functionToTest = function() {
  Name.get($scope.nameId).then(function(name){
    return name;
  }).then(doSomething);
};

您的测试

it('should add the name to the list when Name.get() is resolved', function() {
  // Arrange
  var getDeferred = $q.defer();
  spyOn(mockName, 'get').and.returnValue(getDeferred.promise);

  // Act
  $scope.functionToTest();
  getDeferred.resolve('some name that should be in the list');
  $scope.$apply();

  // Assert
  expect($scope.list).toEqual(['some name that should be in the list']);
});

评论

请注意,以下代码部分不会完成任何任务,可以将其删除而不影响任何内容。

.then(function(name){
  return name;
})

关于angularjs - 如何使用 Jasmine 模拟链式 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840921/

相关文章:

javascript - 咕噜声 : Dist folder not created after grunt command

javascript - Angular JS 获取出现在输入文本中的值

angular - 如何在 jasmine 测试中模拟事件回调触发器

javascript - forEach 中的 promise 返回

javascript - http.jsonp 和 javascript 中的回调

AngularJS - 如何在提交表单时禁用它?

unit-testing - Jasmine spy 不工作

javascript - 在 jasmine-phantomjs 测试中的 html 元素上调用 click() 函数

javascript - AngularJS 等待简单的 promise 得到解决

javascript - 将已解决的 promise 分配给变量