如何测试http.post上的.success调用的服务

时间:2015-05-14 08:52:10

标签: javascript angularjs jasmine karma-jasmine angular-http

我有一个控制器,它使用用户名和密码调用执行http.post的服务。在帖子的.success上,我打电话给另一个服务来创建一个cookie。

我相信'我已经创建了一个成功的Jasmine测试来测试POST,但不确定我如何测试cookie服务。

LoginController.js:

app.controller('LoginController', function($scope, $http, signInService, cookieSrv) {

    $scope.LogIn = function(usrnm, pwd) {
        signInService.authUser(usrnm, pwd)
            .success(function (data, status, headers, config) {
                var cookieID = 'myCookie';
                cookieSrv.createCookie(cookieID, data.token, 3, data.redirectUrl);
            })
            .error(function (data, status, headers, config) {
               // Display error message
            }
    }
});

cookieSrv.js

app.service('cookieSrv', function() {
    return {
        createCookie : function(cookieID, token, days, redirectUrl) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }
            else var expires = "";
            document.cookie = cookieID+"="+token+expires+"; path=/";

            window.location.assign(redirectUrl)
        }
    }
});

signInService:

app.service('signInService', function($http) {    
    this.authUser = function (usrnm, pwd) {    
        return $http.post('/api/json/authenticate', {}, {
            headers: {
                'Content-Type': 'application/json',
                'X-app-Username': usrnm,
                'X-app-Password': pwd
            }
        });
    };
});

单元测试:

describe('Controller: LoginController', function() {

    beforeEach(module('myApp'));

    beforeEach(inject(function($controller, $rootScope, signInService, $httpBackend){
        this.$httpBackend = $httpBackend;
        this.scope = $rootScope.$new();
        $controller('LoginController', {
            $scope: this.scope,
            localSignInService: signInService
        });
    }));    

    describe("successfully logged in", function() {
        it("should redirect to home", function() {

            var fakeResponse = {
                access_token: 'myToken'
            }

            this.$httpBackend.expectPOST('/api/json/authenticate', {} , function(headers) {
                return {
                    'Content-Type': 'application/json',
                    'X-app-Username': 'tomcat',
                    'X-app-Password': 'tomcat'
                };
            }).respond(200, fakeResponse);

            this.scope.LogIn("tomcat","tomcat");
            this.$httpBackend.flush();
            expect(fakeResponse.access_token).toEqual("myToken");
        });
    });
});

更新:

上面我得到错误:

ERROR Some of your tests did a full page reload! 

一些研究表明这是因为cookie服务中的window.location.assign。如果我注释掉这一行,测试运行正常,没有上面的错误。

0 个答案:

没有答案