我有一个单元测试问题,使用Angular (v 9)、Jest (24.9.0)和一个ECMAScript模块(dialog-polyfill (v 0.5.1) )。这个polyfill增加了对 HTMLDialogElement
. 问题是,它有一个方法 registerDialog
当对话框在DOM中时需要被调用。它把对话框元素作为唯一的参数。我创建的这个服务,注册了对话框并将其添加到一个数组中。所有的实现都能完美地工作,但是测试失败了,因为它不知道polyfill是什么。我一直得到以下错误。
TypeError: 不能读取未定义的属性'registerDialog'。
createElement
在Jest测试中的文档上。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);
});
});
你需要在你的TestBed中提供你的服务。
beforeEach(() => {
TestBed.configureTestingModule({
providers: [DialogService]
});
service = TestBed.inject(DialogService);
});