Jasmin Mock $http (then, catch)

Jasmin Mock $http (then, catch)

本文关键字:catch then Mock http Jasmin      更新时间:2023-09-26

我一直在使用下面的代码来测试下面的代码示例。

function loadAccounts() {
  return AccountCaller.loadAccounts()
  .then(function(response){
    AccountsModel.accounts = response.accounts;
  })
  .catch(function(error){
    ErrorHandler.raise(error);
  });
}
var spy= spyOn(mock, 'loadAccounts').andCallFake(function () {
        return {
            then: function (callback) {
                return callback(response);
            }
        };
    });

上面的代码在'。然后"但是我最近介绍了"。" TypeError: Cannot read property 'catch' of undefined " .

对于如何处理这个问题有什么建议吗?Catch '元素,如果我删除它,那么代码测试运行良好!!

欢呼

在你的then间谍你有return callback(response);,但你的回调不返回任何东西,这就是为什么你得到undefined在你的错误。您返回的东西至少需要有某种catch方法附加到它。你可以这样测试:

var spy= spyOn(mock, 'loadAccounts').andCallFake(function () {
    return {
        then: function (callback) {
            callback(response);
            return {catch: function() {}};
        }
    };
});

^^我不一定会这么做,但它应该会让你朝着正确的方向前进。考虑返回用Promise包装的callback(response)的结果。