Angularjs 如何使用Jasmine模拟连锁承诺?

Angularjs 如何使用Jasmine模拟连锁承诺?,angularjs,jasmine,angular-promise,Angularjs,Jasmine,Angular Promise,我正在为包含以下代码的方法编写单元测试: Name.get($scope.nameId).then(function(name){ Return name; }).then(doSomething); 函数doSomething(name)如下所示 function doSomething(name){ addNametoList(name); } 我不需要测试这部分代码。因为我不能在测试中忽略它(或者我可以?),所以我需要模拟它。我嘲笑了第一个承诺 spyOn(mockN

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

Name.get($scope.nameId).then(function(name){
    Return name;
}).then(doSomething);
函数doSomething(name)如下所示

function doSomething(name){
    addNametoList(name);
}
我不需要测试这部分代码。因为我不能在测试中忽略它(或者我可以?),所以我需要模拟它。我嘲笑了第一个承诺

 spyOn(mockName, 'get').and.returnValues($q.resolve({"Mike"})); 
并且认为它会通过第二个
传播,然后(doSomething)
但是
name
在函数
addNametoList
中是
未定义的

我想我也必须模仿一些东西,但我不知道如何把它们连在一起

我不需要测试这部分代码。因为我不能忽视 在我的测试中(或者我可以?),我需要模仿它。我嘲笑了第一个 允诺

在国际海事组织,没有必要测试这些设置作为一个整体。 单独测试每个单元

比如说

A = () => {
  ...
}

B = () => {
  ...
}

C = () => {
  ...
}
现在我们有了F,它叫做B&C

F = () => A(B(C))
还是你的情况

F = () => A().then(B).then(C)
我们可以测试F,但它需要一些设置,而且很脆弱。 最好测试A、B和C(它们对F的覆盖范围适当)并忽略F。

您的(部分)控制器代码

$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']);
});
评论

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;
})

你没有收到错误吗?带大写的
返回
对我来说似乎是个打字错误。它是如何解决的?你会在茉莉花测试结束时回复承诺吗?是的,我意识到代码中有一些输入错误。经过两天的调试,我终于发现这是因为我没有在$q.resolve()中正确设置对象。除此之外,模仿第一个承诺确实会传播到第二个
。然后(doSomething)
。感谢您花时间回复。您似乎有输入错误-
和.returnValues
。。。那不应该是
和.returnValue
吗?编辑:Nevermind,抱歉,
returnValues
在最近的Jasmine版本中存在。。。