【发布时间】:2019-02-10 15:26:00
【问题描述】:
我正在使用 Angular Universal。根据我是在服务器还是浏览器平台上运行,我有一个行为不同的路由的守卫。这是警卫:
export class UniversalShellGuard implements CanActivate {
private isBrowser: boolean;
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
console.log('PLATFORM_ID = ' + platformId);
this.isBrowser = isPlatformBrowser(this.platformId);
}
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
return !this.isBrowser;
}
}
如您所见,守卫正在注入PLATFORM_ID,并使用它来确定他是否canActivate()。
现在,我想为守卫编写一个简单的单元测试并执行以下操作:
describe('UniversalShellGuard', () => {
let guard: UniversalShellGuard;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
UniversalShellGuard,
// Idea: for now I just want to test the behaviour if I would be on the browser, so I would just use a fixed value for PLATFORM_ID
{ provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID },
],
});
guard = TestBed.get(UniversalShellGuard);
});
it('should deny', () => {
expect(guard.canActivate()).toBe(false);
});
});
但它给出了以下错误:
ERROR in ./src/app/universal-shell.guard.spec.ts
Module not found: Error: Can't resolve '@angular/common/src/platform_id' in '/my-app-path/src/app'
@ ./src/app/universal-shell.guard.spec.ts 4:0-70 11:50-69
@ ./src sync \.spec\.ts$
@ ./src/test.ts
我什至尝试了一个简单直接的防护结构,不使用角度TestBed:
it('should deny', () => {
const guard = new UniversalShellGuard(PLATFORM_BROWSER_ID);
expect(guard.canActivate()).toBe(false);
});
同样的错误。
有没有办法为PLATFORM_ID 提供一个固定值,以便正确地对这样的守卫进行单元测试?
【问题讨论】:
标签: angular unit-testing guard angular-universal