Search code examples
angularangular-materialjasminekarma-jasminekarma-runner

Angular test cannot find the open dialog


I have an angular component (HostComponent) that contains some buttons which should open a dialog. I am writing a test for this HostComponent using Angular's TestBed. In the test, I select the button, click it and try to assert that a dialog is opened. When I run the test in browser (since Karma serves the test), I can see that a dialog successfully opens, however my test still fails with the error:

Error: Failed to find element matching one of the following queries:
    (MatDialogHarness with host element matching selector: ".mat-dialog-container")

Here's a drilled down version of the spec:

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();

    }));
});

Here's the screenshot that shows that the dialog is opened even though the tests fail:

enter image description here

I'm really quite confused with Angular's testing features and I've tried asking a similar question before with no luck, so I'm really hoping to be luckier this time.


Solution

  • dialogs are rendered outside of the component fixture, so the fix here would be to use documentRootLoader instead of the simple fixture one

      loader = TestbedHarnessEnvironment.documentRootLoader(fixture);