在角度业力测试中无法读取未定义的属性

时间:2017-09-04 15:14:10

标签: javascript angularjs karma-jasmine angular-services

我正在测试一个服务函数,该函数会进行大量$http.get()次调用。正在测试的实际函数返回一个promise。目前,测试失败了response is undefined

以下是测试:

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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

基于this帖子,我已使用以下代码解决了我的问题(请原谅从书到用户的上下文更改):

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