Cannot read property of undefined in angular karma test

寵の児 提交于 2019-12-11 15:36:27

问题


I am testing a service function which makes numerous $http.get() calls. The actual function under test returns a promise. Currently, the test is failing with response is undefined.

Here is the test:

it('should return the list of catalogues', inject(function ($q, bookService) {
    var list;
    var deferred = $q.defer();
    var promise = deferred.promise;

    promise.then(function (response) {
        list = response.success; // Cannot read property 'success' of undefined
    });

    bookService.getCatalogues().then(function (response) {
        deferred.resolve(response); // this line is hit first
    });

    $httpBackend.flush();

    expect(list).toEqual(listOfBooks); // listOfBooks is defined outside test
}));

What am I doing wrong?


回答1:


Based on this post I have resolved my problem with the following code (please forgive the change in context from book to user):

    describe('user-service', function () {
        var $httpBackend, $q, $rootScope;
        var mockUserData = { "d": { "firstName": "Matt", "lastName": "Lenny" };

        beforeEach(module('users'));

        beforeEach(inject(function (_$httpBackend_,_$q_,_$rootScope_) {
            $httpBackend = _$httpBackend_;
            $q = _$q_;
            $rootScope = _$rootScope_;

            $httpBackend.when('GET', /(.*)\/user\/api/).respond(200, mockUserData);
        }));

        it('should return the user object', inject(function (userService) {
            var user;

            var deferred = $q.defer();
            var promise = deferred.promise;

            promise.then(function (response) {
                user = response;
            });

            userService.getUserInfo().then(function (response) {
                deferred.resolve(response);
            });

            $rootScope.$digest();

            $httpBackend.flush();

            expect(user).toEqual(mockUserData.d);
        }));
    });


来源:https://stackoverflow.com/questions/46039953/cannot-read-property-of-undefined-in-angular-karma-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!