I have created an abstraction for the Navigator object:
export const NAVIGATOR: InjectionToken<Navigator> = new InjectionToken<Navigator>(
'An abstraction over window.navigator object',
{
factory: () => inject(WINDOW).navigator,
},
);
And also, an abstraction for the Window object:
import { inject, InjectionToken } from '@angular/core';
import { DOCUMENT } from '@angular/common';
export const WINDOW: InjectionToken<Window> = new InjectionToken<Window>(
'An abstraction over global window object',
{
factory: () => {
const { defaultView }: any = inject(DOCUMENT);
if (!defaultView) {
throw new Error('Window is not available');
}
return defaultView;
},
},
);
I require these abstractions in order to mock providers for testing classes. However, whenever I inject the Navigator Token into a service like this:
export class MyService {
constructor(
@Inject(NAVIGATOR) private navigator: Navigator,
) {}
}
And run unit tests, I encounter the following error:
ReferenceError: Navigator is not defined
3 | constructor(
> 4 | @Inject(NAVIGATOR) private navigator: Navigator,
| ^
6 | ) {}
My tsconfig.ts configuration is as follows:
{
"compilerOptions": {
"allowJs": true,
...
}
}
Similarly, my tsconfig.spec.ts looks like this:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
...
]
}
}
Any suggestions on how to resolve this issue?