如何对一个主要负责重定向到应用程序外部页面的Angular服务进行单元测试

How to unit test an Angular Service whose main responsibility is to redirect to a page outside of the application?

本文关键字:外部 应用程序 Angular 单元测试 服务 重定向 一个      更新时间:2023-09-26

我有一个服务,其主要职责是重定向到我们的登录页面,这是分开的,因为我们做登录作为一个服务。

function redirectToMembership() {
    var returnURL = $location.host();
    returnURL+="/#/Authorization";
    $window.location.href=EnvironmentConfigConstants.membershipURL + "?ReturnURL="+returnURL;
}

它所做的是获取当前主机并将/#/Authorization附加到末尾,然后重定向到成员URL,并将其作为returnURL。

Authorization是一种状态,用于处理从成员关系返回的会话令牌和userID。

我的问题是:

我应该如何进行单元测试?

我有一种预感,我需要监视你的$location。href并验证它是否被当前位置调用,但每当我触发membershipService.redirectToMembership时,phantomJS崩溃。

到目前为止,这是我的测试:

describe('redirectToMembership', function () {
    beforeEach(function () {
        spyOn($location,'host').andReturn('localhost');
        spyOn($location,'port').andReturn(80);
        spyOn($window.location,'href');
    });
    it('should redirect to Membership (duh)', function () {
        var success = false;
        membershipService.redirectToMembership();
        expect($window.location.href).toBe('this');
        $rootScope.$digest();
    }) ;
});

然而,这给了我两个错误:

'undefined' is not a function (evaluating spyOn($location,'host').andReturn('localhost')')

'undefined' is not an object (evaluating 'returnURL.indexOf')

我做错了什么吗?

我不打算关注为什么phantomjs崩溃,但这里的想法是模拟您的依赖关系而不是实际实例,即模拟$location$window,然后返回值作为您的测试期望。重定向是如何发生的,如何返回主机等等。不应该成为你服务的问题,所以直接模仿它们。

像这样:

describe('redirectToMembership', function () {
    var $location, 
        $window = {location:{href:""}}, 
        host="localhost", 
        port="80",
        membershipService,
        $rootScope;
    beforeEach(function () {
        //Set up mocks
        module('myModule',function($provide){
           //create a spy object with 2 functions
           $location = jasmine.createSpyObj('location',['host', 'port']);
           $location.host.and.returnValue(host);
           $location.port.and.returnValue(port);
           //Set the mock object created above
           $provide.value('$location', $location) ;
           //Set the mock object
           $provide.value('$window', $window) ;
       });
       //get instances
       inject(function(_membershipService_, _$rootScope_){
           membershipService = _membershipService_;
           $rootScope = _$rootScope_; 
       });
    });
    it('should redirect to Membership (duh)', function () {
        var success = false;
        membershipService.redirectToMembership();
        expect($window.location.href).toBe(ExpectedContructedURL);
        $rootScope.$digest(); //You may not need this
    });
});