测试角度身份验证防护重定向

时间:2019-03-27 16:46:53

标签: angular jasmine jasmine2.0 spyon

我有一个authenticated角警卫队

@Injectable({
    providedIn: 'root'
})
export class AuthenticatedGuard implements CanActivate, CanActivateChild {
    constructor(@Inject('Window') private window: Window,
                private readonly authenticationService: AuthenticationService) {}

    canActivate(): boolean {
        if (!this.authenticationService.isAuthenticated) {
            this.window.location.href = '/login';
        }
        return allowed;
    }

    canActivateChild(): boolean {
        return this.canActivate();
    }
}

我在注入的模拟窗口中进行了这些测试,以使测试窗口不会重定向,因此我可以检查href是否已设置

const MockWindow = {
    location: {
        _href: '',
        set href(url: string) {
            //console.log('set!', url)
            this._href = url;
        },
        get href(): string {
            //console.log('get!', this._href)
            return this._href;
        }
    }
};

describe('Guard: authenticated', () => {
    let redirectSpy: jasmine.Spy;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                AuthenticatedGuard,
                AuthenticationService,
                {provide: 'Window', useValue: MockWindow}
            ]
        });
        redirectSpy = spyOnProperty(MockWindow.location, 'href', 'set');
    });

    afterEach(() => {
        sessionStorage.removeItem('token');
    });

    it('should allow route activation when both the token is set', inject([AuthenticatedGuard], (guard: AuthenticatedGuard) => {
        sessionStorage.setItem('token', 'foo');
        expect(guard.canActivate()).toEqual(true);
        expect(guard.canActivateChild()).toEqual(true);
        expect(redirectSpy).not.toHaveBeenCalled();
    }));

    it('should disallow route activation when the token is not set', inject([AuthenticatedGuard], (guard: AuthenticatedGuard) => {
        expect(guard.canActivate()).toEqual(false);
        expect(guard.canActivateChild()).toEqual(false);
        expect(redirectSpy).toHaveBeenCalledWith('/login'); //<-- this fails!
    }));

...

expect(redirectSpy).toHaveBeenCalledWith('/login');总是失败,它根本没有被调用。与expect(redirectSpy).toHaveBeenCalled();相同-我在做什么错?我希望能够测试此重定向,但是我不希望我的业力测试浏览器实际重定向。

(仅供参考:我需要使用window.location.href而不是角度路由器,以便我们可以将用户定向到处理登录的其他非角度应用程序)

1 个答案:

答案 0 :(得分:0)

我发现一些有效的方法消除了间谍的需要。现在,我只是通过调用get {@ 1}}从警卫那里注入了窗口提供程序,效果很好!

请让我知道是否可以做得更好!

TestBed.get('Window')
相关问题