gpt4 book ai didi

Angular 4 : test if window. location.href 已被调用

转载 作者:行者123 更新时间:2023-11-28 19:57:50 25 4
gpt4 key购买 nike

我有一个 AuthGuard 服务,负责检测用户是否已登录。如果未登录,我会将用户重定向到我们的 oauth 提供程序 url。

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

import { environment } from './../../environments/environment';
import { Session } from './../core/security/session.service';

@Injectable()
export class AuthGuard implements CanActivate {
/**
* Class constructor.
* @constructor
*
* @param {Session} - Instance of session.
*/
constructor(private session: Session) {}

/**
* Method to implements from CanActivate interface.
* Check if a user is authenticated.
*
* @return {boolean}
*/
canActivate(): boolean {
if (this.session.isActive()) {
return true;
}

this.redirectToProvider();
return false;
}

/**
* Redirect to Identity unauthorized url.
*/
private redirectToProvider() {
const unauthorizeUrl = environment.api.identity.unauthorizeUrl;
window.location.href = unauthorizeUrl;
}
}

我想知道当 Session 不存在时是否调用了 window.location.href。这是我到目前为止所做的:

import { TestBed, async, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AuthGuard } from './auth-guard.service';
import { Session } from './../core/security/session.service';

describe('AuthGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthGuard,
Session
],
imports: [RouterTestingModule]
});
});

describe('.canActivate', () => {
describe('active session', () => {
it('returns true',
async(inject([AuthGuard, Session], (guard, session) => {
session.set({ name: 'user' });

expect(guard.canActivate()).toBeTruthy();
})
));
});

describe('no session', () => {
it('redirects the user',
async(inject([AuthGuard, Session], (guard, session) => {
spyOn(window.location, 'href');
session.destroy();

expect(guard.canActivate()).toBeFalsy();
expect(window.location.href).toHaveBeenCalled();
})
));
});
})
});

但它给了我以下错误:

Failed: <spyOn> : href is not declared writable or has no setter

有没有办法模拟窗口对象来实现这个,或者我是否需要依赖一些特殊的类来处理这种重定向,以便我可以在测试中注入(inject)它们?

最佳答案

您可以将 window 作为注入(inject) token 注入(inject)。 Angular 在@angular/common 中还有一个 DOCUMENT DI token ,您可以直接将其与 document.location.href 一起使用。

import { InjectionToken } from '@angular/core';

export const WindowToken = new InjectionToken('Window');
export function windowProvider() { return window; }

app.module.ts中添加:

providers: [
...
{ provide: WindowToken, useFactory: windowProvider }
]

并将其注入(inject)到服务中:

constructor(@Inject(WindowToken) private window: Window, private session: Session)

在您的规范文件中,模拟窗口对象并对其进行测试。我创建了一个包含两个测试服务(一个依赖于另一个)的工作示例。该服务是使用 Angular 的静态注入(inject)器创建的:

import { TestBed } from '@angular/core/testing';

import { CustomHrefService } from './custom-href.service';
import {AppModule} from '../app.module';
import {WindowToken} from './window';
import {Injector} from '@angular/core';
import {CustomHref2Service} from './custom-href-2.service';

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

describe('CustomHrefService', () => {
let service: CustomHrefService;
let setHrefSpy: jasmine.Spy;

beforeEach(() => {
setHrefSpy = spyOnProperty(MockWindow.location, 'href', 'set');

const injector = Injector.create({
providers: [
{ provide: CustomHrefService, useClass: CustomHrefService, deps: [WindowToken, CustomHref2Service]},
{ provide: CustomHref2Service, useClass: CustomHref2Service, deps: []},
{ provide: WindowToken, useValue: MockWindow}
]
});
service = injector.get(CustomHrefService);
});

it('should be registered on the AppModule', () => {
service = TestBed.configureTestingModule({ imports: [AppModule] }).get(CustomHrefService);
expect(service).toEqual(jasmine.any(CustomHrefService));
});

describe('#jumpTo', () => {
it('should modify window.location.href', () => {
const url = 'http://www.google.com';
service.jumpTo(url);
expect(setHrefSpy).toHaveBeenCalledWith(url);
});
});
});

关于Angular 4 : test if window. location.href 已被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44880851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com