din*_*ena 2 jasmine karma-runner karma-jasmine angular-material angular
我有一个角度组件 ( HostComponent),其中包含一些应该打开对话框的按钮。我正在HostComponent使用 Angular 的TestBed. 在测试中,我选择该按钮,单击它并尝试断言打开了一个对话框。当我在浏览器中运行测试时(因为 Karma 提供测试服务),我可以看到对话框成功打开,但是我的测试仍然失败并出现错误:
Error: Failed to find element matching one of the following queries:
(MatDialogHarness with host element matching selector: ".mat-dialog-container")
Run Code Online (Sandbox Code Playgroud)
这是该规范的深入版本:
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();
}));
});
Run Code Online (Sandbox Code Playgroud)
这是显示即使测试失败但对话框仍打开的屏幕截图:
我真的对 Angular 的测试功能很困惑,之前我也曾尝试问过类似的问题,但没有成功,所以我真的希望这次能幸运一些。
对话框在组件固定装置之外呈现,因此此处的修复方法是使用 documentRootLoader 而不是简单的固定装置
loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1082 次 |
| 最近记录: |