Jasmine - TypeError: Unable to get "catch" property from undefined or null reference

I am trying to create a unit test to call a service in my method. unit test returns the following error:

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

The controller method I'm testing is:

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

My unit test looks like this:

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

When I remove the ".catch (function (error)" instruction from my controller method, the test passes. It seems I need to implement catch on my spy, but I can’t figure out how to do this.

+4
source share
2 answers

Methods thenand catchcome from the promise template, which is implemented in AngularJS service $q.

() . - $q.when(value). , value.

Try:

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

, $q .

Angular.

+3

, . . .

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

, , .

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

, , . , .

0

Source: https://habr.com/ru/post/1628353/


All Articles