AngularJS - 具有 header 响应的单元测试

AngularJS - Unit test with header response

当用户在我的网站上成功登录时,我的后端会检索到 'x-token'。在我的前端,我做了一个简单的验证,获取这个令牌并设置:$rootScope.authenticated = true; 如果令牌不存在于 header 响应中,我的前端设置的任何原因:$rootScope.authenticated = false;

我的控制器

signinService
    .signin(datafromForm)
    .then(function (data) {
        if ( $myTokenManager.save(data.headers('x-token')) ) {
            $rootScope.authenticated = true;
        } else {
            $rootScope.authenticated = false;
            // Unit test is sent it here :(
        }

    });

这很完美,现在我需要对此方法进行单元测试,但我的测试没有正确生成或设置 header 响应。我在考试中做错了什么?

describe('Testing controllers', function() {

    describe('MyController unit test', function() {

        var $httpBackend, $rootScope, createController, authRequestHandler, datafromForm;

        beforeEach(module('myapp'));

        beforeEach(inject(function($injector) {

            $httpBackend = $injector.get('$httpBackend');

            authRequestHandler = $httpBackend
                                    .when(
                                        'POST',
                                        'http://mywebapp:8080/loginuser',
                                        {"username":"admin", "password":"admin"}
                                    ).respond({'x-token': 'XXX'});

            $rootScope = $injector.get('$rootScope');
            var $controller = $injector.get('$controller');

            createController = function() {
                return $controller('MyController', {'$scope' : $rootScope});
            }
        }));

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

        //
        it('should authentication user', function() {

            var controller = createController();

            //
            $rootScope.username = "admin";
            $rootScope.password = "admin";

            datafromForm = {
                username: $rootScope.username,
                password: $rootScope.password
            };

            $httpBackend.expectPOST(
                'http://mywebapp:8080/loginuser',
                {"username":"admin", "password":"admin"}
            ).respond(
                200, 
                {'x-token': 'XXX'}
            );

            $rootScope.login(formData);
            $httpBackend.flush();
            expect($rootScope.authenticated).toBe(true); // This is getting false :(
        });





    });

});

我正在关注 angular 文档中的 this 示例。

respond() 函数的记录签名是

function([status,] data[, headers, statusText])

在你的第一个respond()中,你只传递数据,没有header:

respond({'x-token': 'XXX'});    

在你的第二个respond()中,你只传递状态和数据,仍然没有header:

respond(
    200, 
    {'x-token': 'XXX'}
);