angularjs - Jasmine - 类型错误 : Unable to get property 'catch' of undefined or null reference

标签 angularjs unit-testing jasmine

我正在尝试在我的方法中为服务调用创建单元测试。单元测试返回以下错误:

TypeError: Unable to get property 'catch' of undefined or null reference

我正在测试的 Controller 方法:

$scope.getAsset = function (id) {
    if ($scope.id != '0') {
        assetFactory.getAsset($scope.id)
        .then(function (response) {
            $scope.asset = response.data;
        })
        .catch(function (error) {
            alertService.add('danger', 'Unable to load asset data: ' + error.statusText + '(' + error.status + '). Please report this error to the application administrator');
        });
    }
};

我的单元测试如下:

it('method getAsset() was called', function () {
    var asset = { AssetId: 'TEST123' };
    var spy = spyOn(assetFactory, 'getAsset').and.callFake(function () {
        return {
            then: function (callback) {
                return callback(asset);
            }
        };
    });
    // call the controller method
    var result = scope.getAsset();
    // assert that it called the service method. must use a spy
    expect(spy).toHaveBeenCalled();
});

当我从 Controller 方法中删除“.catch(function (error)”语句时,测试通过。看来我必须在我的 spy 中实现 catch,但我不知道如何实现。

最佳答案

thencatch 方法来自于 AngularJS 中由 $q 实现的 Promise 模式。服务。

你的模拟(伪造)方法也应该返回一个 promise 。最简单的方法是使用 $q.when(value)。它创建的 Promise 会立即解析为给定的

尝试:

var response = {data: asset};
var spy = spyOn(assetFactory, 'getAsset').and.returnValue($q.when(response));

当然,您需要在测试中注入(inject)$q

也值得一读How to unit-test promise-based code in Angular .

关于angularjs - Jasmine - 类型错误 : Unable to get property 'catch' of undefined or null reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35345606/

相关文章:

angularjs - 如何在 Angular/Node 应用程序中正确发送和接收表单数据

html - 如何使用 vw 单位在 css 中创建响应圈?

testing - 如何使用 runSaga/redux-saga 接收拍摄

javascript - 寻找与 Nashorn 的 jjs 解释器一起使用的 javascript 单元测试套件

php - 使用 ZfcUser 对 Controller 进行简单的 ZF2 单元测试

javascript - 测试是否在 Jasmine 中捕获了异常

node.js - 如何通过命令行设置 karma 配置条目?

javascript - 要求未找到 Angular Directive(指令) Controller

javascript - 无法在 'FileList' 上设置索引属性 : Index property setter is not supported. v

javascript - 如何将评估值传递给自定义元素指令?