In my directive, I use dependency injection to access the DOCUMENT
and set up an event listener:
constructor(@Inject(DOCUMENT) private document: Document) {}
ngOnInit() {
this.document.addEventListener('click', this.clicked, true);
}
@Bound // custom decorator, you can ignore it
private clicked() {
// do stuff
}
Now, I need to write a test that verifies whether the injected document
has had the addEventListener
method called on it:
it('should add a click event listener to document on ngOnInit', async(() => {
// Override the template and get the fixture
overrideAndCompileComponent(LibTestComponent, `
<div libClickOutsideDocumentListener></div>
`).then((fixture) => {
const spy = spyOn<any>(fixture.componentRef.injector.get(Document), 'addEventListener');
expect(spy).toHaveBeenCalled();
});
}));
However, when running the test, I encounter the following error:
StaticInjectorError(Platform: core)[Document]
The problem seems to be related to how I'm providing the DOCUMENT
. When I include it in the providers
array of the TestBed
configuration like this:
TestBed.configureTestingModule({
... excluded code ...
providers: [
{ provide: DOCUMENT, useValue: Document }
]
});
I receive an internal Angular error:
el.querySelectorAll is not a function
It appears that the value provided for document
is incorrect. Despite researching Angular documentation, I haven't found a solution yet.
What am I missing here?