我有一个关于 Angular 5 的项目,但遇到了以下问题。我有一个组件 ComponentWithSnackBar 触发显示小吃店:
showSnackBar() {
this.snackBar.open('Message text', 'Close', {
duration: 5000,
verticalPosition: 'top',
});
}
它按预期工作。但我不知道如何测试它。我尝试编写测试:
describe('ComponentWithSnackBar', () => {
let snackBar: MatSnackBar;
let overlayContainer: OverlayContainer;
let overlayContainerElement: HTMLElement;
function createComponent<T>(component: Type<T>, providers: Provider[] = [], declarations: any[] = []): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [AppModule, RouterTestingModule, NoopAnimationsModule],
declarations: declarations,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers,
}).compileComponents();
inject([MatSnackBar, OverlayContainer], (sb: MatSnackBar, oc: OverlayContainer) => {
snackBar = sb;
overlayContainer = oc;
overlayContainerElement = oc.getContainerElement();
})();
return TestBed.createComponent<T>(component);
}
it(`Should display snack-bar`, fakeAsync(() => {
const fixture = createComponent(ComponentWithSnackBar);
const component: ComponentWithSnackBar = fixture.debugElement.componentInstance;
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('button')); //button which triggers method showSnackBar
button.triggerEventHandler('click', null);
fixture.detectChanges();
flush();
const messageElement = overlayContainerElement.querySelector('snack-bar-container');
expect(messageElement.textContent).toContain('Message text');
}));
});
结果我得到错误
TypeError:无法读取 null 的属性“textContent”
我做错了什么?感谢提前!