Reputation: 314
I have a unit testing question using Angular (v 9), Jest (24.9.0), and an ECMAScript Module (dialog-polyfill (v 0.5.1) ). This polyfill adds support for the HTMLDialogElement
. The issue is, it has a method registerDialog
that needs to be called when the dialog is in the DOM. It takes the dialog element as it's only parameter. This service that I've created, registers the dialog and adds it to an array. Everything works perfectly with the implementation, but the tests fail because it doesn't know what the polyfill is. I keep getting the following error:
TypeError: Cannot read property 'registerDialog' of undefined
createElement
on the document within the Jest test.import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import dialogPolyfill from 'dialog-polyfill';
@Injectable({
providedIn: 'root'
})
export class DialogService {
public dialogs$: BehaviorSubject<HTMLDialogElement[]> = new BehaviorSubject<
HTMLDialogElement[]
>([]);
private dialogs: [] = [];
constructor() {}
register(dialog: HTMLDialogElement) {
dialogPolyfill.registerDialog(dialog);
this.dialogs$.next([...this.dialogs, dialog]);
}
}
import { TestBed } from '@angular/core/testing';
import { DialogService } from './dialog.service';
describe('DialogService', () => {
let service: DialogService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(DialogService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should register a dialog', () => {
expect(service.dialogs$.getValue().length).toBe(0);
service.register(document.createElement('dialog'));
expect(service.dialogs$.getValue().length).toBe(1);
});
});
Upvotes: 0
Views: 1959
Reputation: 9377
You need to provide your service in your TestBed:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [DialogService]
});
service = TestBed.inject(DialogService);
});
Upvotes: 3