I am using Angular Universal. I have a guard for a route that behaves differently depending on if I am running on the server or the browser platform. Here is the guard:
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;
}
}
As you can see, the guard is injecting PLATFORM_ID
and uses it to determine if he canActivate()
or not.
Now, I wanted to write a simple unit test for the guard and did the following:
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);
});
});
But it gives the following error:
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
I even tried a simple and straight forward construction of the guard, without using the angular TestBed
:
it('should deny', () => {
const guard = new UniversalShellGuard(PLATFORM_BROWSER_ID);
expect(guard.canActivate()).toBe(false);
});
Same error.
Is there any way to provide a fixed value for PLATFORM_ID
for properly unit-testing such a guard?
isPlatformBrowser
method should receive an Object but mocking with a string is just fine. – Chaille