【发布时间】:2021-09-14 12:34:48
【问题描述】:
我有一个角组件 (HostComponent),其中包含一些应该打开对话框的按钮。我正在使用 Angular 的 TestBed 为这个 HostComponent 编写一个测试。在测试中,我选择按钮,单击它并尝试断言对话框已打开。当我在浏览器中运行测试时(因为 Karma 服务于测试),我可以看到一个对话框成功打开,但是我的测试仍然失败并出现错误:
Error: Failed to find element matching one of the following queries:
(MatDialogHarness with host element matching selector: ".mat-dialog-container")
这是规范的深入版本:
describe('HostComponent', () => {
let fixture: ComponentFixture<HostComponent>;
let loader: HarnessLoader;
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [HostComponent, MyTestDialogComponent],
providers: [FormBuilder],
imports: [MatDialogModule, NoopAnimationsModule, MatAutocompleteModule, ReactiveFormsModule, MatSelectModule, MatInputModule]
}).createComponent(WidgetGroupConfigComponent);
loader = TestbedHarnessEnvironment.loader(fixture);
fixture.detectChanges();
});
const buttonWithText = (text: string) => {
const allButtons: HTMLButtonElement[] = fixture.debugElement.nativeElement.querySelectorAll('button');
const allButtonsArr = [...allButtons];
return allButtonsArr.find(button => button.innerText === text);
};
it('Opens the dialog when button is clicked', fakeAsync(async () => {
const testButton = buttonWithText('TestTimberDevice01')!;
expect(testButton).toBeDefined(); // passes
testButton.click();
tick();
fixture.detectChanges();
const dialog = await loader.getHarness(MatDialogHarness); // fails here
expect(dialog).toBeDefined();
}));
});
下面的屏幕截图显示,即使测试失败,对话框也已打开:
我真的对 Angular 的测试功能感到很困惑,我尝试过问一个类似的问题 before 却没有运气,所以我真的希望这次能更幸运一些。
【问题讨论】:
-
为什么?对不起,我刚刚阅读了整个链接(尽管我之前已经阅读过),但我没有找到任何可以帮助解决我上面描述的问题的东西。你有什么特别的想法吗?
标签: angular angular-material jasmine karma-jasmine karma-runner