测试angularjs $ httpbackend和$ resource

时间:2014-07-17 20:00:14

标签: angularjs unit-testing

*更新 - 请参阅帖子结尾*

我有一个依赖于服务的控制器。该服务封装了$resource。这是代码

app.controller('charactersController', function ($scope, $routeParams, $location, marvelRepository) {
    var page = parseInt($routeParams.pageNumber);

    marvelRepository.fetch(page - 1).then(function (data) {
        $scope.characters = data.results;
        $scope.paging = {
            page: page,
            total: data.total,
            pageSize: data.limit
        };
    });

    $scope.goto = function (pageNumber) {
        $location.path('/characters/' + pageNumber);
    };
});

marvel.service('marvelRepository', function (hash, $resource) {
    var extended = ng.extend(hash.authenticate(), { id: '@id' });
    var characters = $resource('http://gateway.marvel.com/v1/public/characters/:id', extended);

    return {
        get: function (characterId) {
            return characters
                .get({ id: characterId })
                .$promise
                .then(function (response) {
                    if (response.code !== 200) {
                        throw response;
                    }

                    return response.data.results[0];
                });
        },
        fetch: function (pageIndex) {
            return characters
                .get({ limit: 20, offset: pageIndex * 20 })
                .$promise
                .then(function (response) {
                    if (response.code !== 200) {
                        throw response;
                    }

                    return response.data;
                });
        }
    };
});

哈希依赖项为marvel api创建身份验证参数:public key,timestamp&哈希值。

网站工作,我可以显示一个字符列表。现在我正在尝试编写测试(因为角度提升了易测试性......)

这是我的测试

describe("Angular Demo - Test", function () {
    beforeEach(angular.mock.module('demo'));

    describe('requiring Marvel respository', function() {
        var url = 'http://gateway.marvel.com/v1/public/characters?apikey=123&hash=abc123&limit=20&offset=0&ts=20140601073322';
        var httpBackend, location, scope, controller;

        beforeEach(module(function (hashProvider) {
            hashProvider.override({
                apikey: '123',
                ts: '20140601073322',
                hash: 'abc123'
            });
        }));

        beforeEach(inject(function ($httpBackend, $location, $rootScope, $controller) {
            controller = $controller;
            location = $location;
            scope = $rootScope.$new();
            httpBackend = $httpBackend;
        }));

        afterEach(function () {
            //httpBackend.verifyNoOutstandingExpectation();
            //httpBackend.verifyNoOutstandingRequest();
        });

        describe('charactersController', function () {
            var characters;

            beforeEach(function() {
                characters = new Array(20);

                httpBackend.when('get', url).respond({ data: { results: characters, offset: 2, limit: 20, total: 100 } });

            });

            it('should be able to get a page of characters', function () {
                httpBackend.expect('get', url);

                controller('charactersController', { $scope: scope, $routeParams: { pageNumber: 1 } });

                httpBackend.flush();

                expect(scope.characters).toBe(characters);
            });

            it('should be able to configure paging', function () {
                 httpBackend.expect('get', url);

                controller('charactersController', { $scope: scope, $routeParams: { pageNumber: 1 } });

                httpBackend.flush();

                expect(scope.paging.total).toBe(100);
                expect(scope.paging.page).toBe(1);
                expect(scope.paging.pageSize).toBe(20);
            });

            it('should be able to navigate to another page of characters', function () {
                controller('charactersController', { $scope: scope });

                scope.goto(5);

                expect(location.path()).toBe('/characters/5');
            });
        });
    });
});

当我执行测试时,我得到以下结果

  

错误:意外请求:GET   http://gateway.marvel.com/v1/public/characters/1?apikey=123&hash=abc123&ts=20140601073322

     

预计得到   http://gateway.marvel.com/v1/public/characters/1?apikey=123&hash=abc123&ts=20140601073322

     

错误:意外请求:GET   http://gateway.marvel.com/v1/public/characters/1?apikey=123&hash=abc123&ts=20140601073322

     

预计得到   http://gateway.marvel.com/v1/public/characters/1?apikey=123&hash=abc123&ts=20140601073322       在$ httpBackend(/tests/angular-mock.js:1172:13)       在sendReq(/js/angular/angular.js:8286:9)       at $ http.serverRequest(/js/angular/angular.js:8027:16)       在wrappedCallback(/js/angular/angular.js:11574:81)       在wrappedCallback(/js/angular/angular.js:11574:81)       在/js/angular/angular.js:11660:26       在范围。$ eval(/js/angular/angular.js:12724:28)       在Scope。$ digest(/js/angular/angular.js:12536:31)       在函数。$ httpBackend.flush(/tests/angular-mock.js:1447:20)       在对象。 (/tests/tests.js:113:29)

如果我在整个代码中添加控制台语句。我可以看到marvelRepository.fetch(1)被调用了。但是.$promise.then()似乎没有执行。

对我来说没有意义的是错误的前两行。首先,它声明了一个意外的请求,然后它说出了对网址的预期调用。它是相同的网址。

关于我所忽视的任何想法?

*更新* 我更新了测试的结构。设置whenexpect个来电。

我还发现如果将后端呼叫从when('get', ...更改为when('GET', ...,我会收到以下测试错误

undefined: undefined

没有堆栈跟踪或行号,但未定义。检查它所声明的原始错误

Error: Unexpected request: GET url....
Expected get url...

所以我想知道它是否因为比较请求方法的区分大小写而失败。但是,我认为这是一个时间问题。注入服务并调用该方法,但promise.then(cb)不会执行。但也许它没有被解雇因为请求方法不匹配所以$ httpbackend不会返回?

2 个答案:

答案 0 :(得分:0)

在BeforeEach中,您需要使用.when()代替.expect()

httpBackend
.when('GET', 'http://gateway.marvel.com/v1/public/characters?apikey=123&hash=abc123&limit=20&offset=0&ts=20140601073322')
.respond({ data: { results: characters, offset: 2, limit: 20, total: 100 } });

使用.expect()通常在断言中完成,而不是设置。

答案 1 :(得分:0)

终于找到了解决方案。问题是使用承诺和延期执行。我还需要调用$scope.apply()和'$ httpBackend.flush()'

这是一个通过测试

describe('characterController', function () {
    var characterUrl = 'http://gateway.marvel.com/v1/public/characters/1';
    var character;

    beforeEach(function () {
        character = { name: 'Wolverine'};

        httpBackend.whenGET(characterUrl).respond({ data: { results: [character] } });
    });

    it('should be able to get character with id of 1', function () {
        controller('characterController', { $scope: scope, $routeParams: { id: 1 } });

        scope.$apply();//execute promises
        httpBackend.flush(); //process http requests

        expect(scope.character).toEqual(character);
    });
});