无法读取角业力测试中未定义的属性 [英] Cannot read property of undefined in angular karma test

查看:32
本文介绍了无法读取角业力测试中未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

测试如下:

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

我做错了什么?

推荐答案

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

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

这篇关于无法读取角业力测试中未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆