Angularjs jasmine-TypeError:无法获取属性';捕捉';指未定义的或空的引用

Angularjs jasmine-TypeError:无法获取属性';捕捉';指未定义的或空的引用,angularjs,unit-testing,jasmine,Angularjs,Unit Testing,Jasmine,我正在尝试为方法中的服务调用创建单元测试。单元测试返回以下错误: 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 (res

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

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)”语句时,测试通过了。看起来我必须在spy中实现catch,但我不知道如何实现。

then和
catch
方法来自promise模式,该模式由服务在AngularJS中实现

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

尝试:

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


它也值得一读。

我也有这个问题,但上面的解决方案帮不上忙。我的问题有点不同。我像前面一样使用了模拟

jasmine.createSpy('mockFunc()').and.callFake()
然后我用回调函数将其更改为如下所示

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

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

成功了。我在安装控制器和测试通过之前的每个地方都注入了$q。谢谢。
jasmine.createSpy('mockFunc()').and.callFake(function() { })