cypress / blazor testing a confirm dialog sawned from a JsRuntime

536 Views Asked by At

so I am writing automated test using cypress for a blazor app and I keep running into an error while I test a confirm dialog as if cypress is trying to return a function as a value.

the exact error message is "the value 'confirm' is no a function"

here is the snippet I am trying to debug

the .razor has a button called Cancel when the button cancel is pressed a confirmation popup shows up with the options ok and cancel ok takes you to a previous page in the hierarchy. cancel will take you back to the current page/form.

in the .razor file

<button class="btn btn-danger" @onclick="CancelConfirmation" data-cy="buttonCancel">Cancel</button>

later in the file for the @code section

private async Task CancelConfirmation()
{
    bool confirmCancel = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to leave ?");
    if (confirmerCancel)
    {
        navigation.NavigateTo("/");
    }
}

My current test is the following (section that triggers the error)

 cy.get('[data-cy=buttonCancel]').click();
    
    cy.on ('window:confirm', (text) => {
        expect(text).to.contains('Are you sure you want to leave ?')
        return true;
    });

I feel it should work but all it does is raise an error.

1

There are 1 best solutions below

0
Fody On

It looks like your @inject variable does not match the one used in @code.

Also if (confirmerCancel) should be if (confirmCancel).

This worked for me in the Blazor Fiddle

@page "/"

@inject IJSRuntime jsRuntime

<h1>Hello, world!</h1>

<button class="btn btn-danger" @onclick="CancelConfirmation" data-cy="buttonCancel">Cancel</button>

@code{

    private async Task CancelConfirmation()
    {
        bool confirmCancel = await jsRuntime.InvokeAsync<bool>("confirm", "Are you sure?");
        if (confirmCancel)
        {
            // I can't use navigation in Fiddle, so just alerting
            await jsRuntime.InvokeAsync<string>("ShowAlert", "Confirmed!");
        }
    }
}

The test needs to set the event listener before invoking the alert,

cy.on ('window:confirm', (text) => {
  expect(text).to.contains('Are you sure you want to leave ?')
  return true;
})

cy.get('[data-cy=buttonCancel]').click();

or use a stub, better for situation where window:confirm never fires

const stub = cy.stub()  
cy.on ('window:alert', stub)

cy.get('[data-cy=buttonCancel]').click()
  .then(() => {
    expect(stub.getCall(0)).to.be.calledWith('Are you sure you want to leave ?')      
  })