我正在为包含这段代码的方法编写单元测试:
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)
传播但是name
是 undefined
在功能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/