0

I'm trying to test a function call inside a forEach loop, but I get the following error:

Expected a spy, but got Function.

What I don't understand, is that the tests are successful.

it("should emit event", async () => {
    component.type = "confirm";
    fixture.detectChanges();
    spyOn(component.dialogClose, "emit");

    const buttons = await loader.getAllHarnesses(MatButtonHarness);

    buttons.forEach(async (button) => {
        await button.click();
        expect(component.dialogClose.emit).toHaveBeenCalled();
    });
});

if I change the test to test only one button (and not use a foreach), I don't have any errors:

it("should emit event", async () => {
    component.type = "confirm";
    fixture.detectChanges();
    spyOn(component.dialogClose, "emit");

    const button = await loader.getHarness(MatButtonHarness);

    await button.click();
    expect(component.dialogClose.emit).toHaveBeenCalled();
});

Here the part I'm testing:

@Output()
public dialogClose: EventEmitter<boolean> = new EventEmitter<boolean>();
<div mat-dialog-actions [ngSwitch]="type">
    ...
    <ng-container *ngSwitchCase="'confirm'">
        <button mat-button color="warn" (click)="dialogClose.emit(false)">Cancel</button>
        <button mat-raised-button color="accent" (click)="dialogClose.emit(true)">Yes</button>
    </ng-container>
    ...
</div>

Why and what's the issue?

Robouste
  • 3,020
  • 4
  • 33
  • 55

1 Answers1

0

Your test is running the assertions asynchronously, but you do not wait for those assertions to complete before the test ends, so they are likely not being made at all.

If you insist on running all those assertions in the same test you need to await something like a Promise.all for each of the promises in your for each as described here

Using async/await with a forEach loop

or use a done function in the then of the Promise.all or await them in sequence as described in the same post.

If this were my code, I would write individual tests for each button, however.

possum
  • 1,837
  • 3
  • 9
  • 18