In my directive I'm injecting DOCUMENT
and adding 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
}
Then I have a test which needs to grab the injected document
and spy on it to see if addEventListener
was called:
it('should add a click event listener to document on ngOnInit', async(() => {
// Overrides the template and returns the fixture
overrideAndCompileComponent(LibTestComponent, `
<div libClickOutsideDocumentListener></div>
`).then((fixture) => {
const spy = spyOn<any>(fixture.componentRef.injector.get(Document), 'addEventListener');
expect(spy).toHaveBeenCalled();
});
}));
This gives me the following error:
StaticInjectorError(Platform: core)[Document]
The issue is that I cannot figure out how to provide DOCUMENT
properly. If I add the following to TestBed
's providers
array:
TestBed.configureTestingModule({
... excluded code ...
providers: [
{ provide: DOCUMENT, useValue: Document }
]
});
I get the following (internal angular) error:
el.querySelectorAll is not a function
So it seems to override document
with an incorrect value. I've been digging through the Angular docs but cannot find a solution..
What am I doing wrong?