【问题标题】:jasmine - TypeError: Unable to get property 'catch' of undefined or null referencejasmine - TypeError:无法获取未定义或空引用的属性“捕获”
【发布时间】:2016-10-13 19:53:38
【问题描述】:

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

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

我正在测试的控制器方法:

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

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

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    thencatch 方法来自 Promise 模式,该模式在 AngularJS 中由 $q 服务实现。

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

    试试:

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

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

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

    【讨论】:

    • 做到了。我在设置控制器的 beforeEach 中注入了 $q 并且测试通过了。谢谢。
    【解决方案2】:

    我也遇到了这个问题,但是上面的解决方案无济于事。我的问题有点不同。我使用的是前面的模拟。

    jasmine.createSpy('mockFunc()').and.callFake()
    

    然后我用回调函数将其更改为如下。

    jasmine.createSpy('mockFunc()').and.callFake(function() { })
    

    我知道这听起来很疯狂,但这解决了我的问题。如果您犯了同样的错误,也可以尝试一下。

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2014-08-01
      相关资源
      最近更新 更多