bunit Validate NavigationManager Url on async button click

Viewed 225

I have a component that has two buttons, one to delete a customer and then returns to the customer list and the second a cancel button that returns to a list of customers.

<td class="text-right">
    <button id="Delete_Cust" class="btn btn-primary" @onclick="Delete">Delete Customer</button>
    <button id ="Cancel_Btn" class="btn btn-secondary" @onclick="Cancel">Cancel</button>
</td>

[Parameter]
public int Id { get; set; }

protected async Task Delete()
{
    await _customer.DeleteCustomerAsync(Id); // THIS IS MOCKED AND RETURNS TRUE
    NavigationManager.NavigateTo("/customers");
}

void Cancel()
{
    NavigationManager.NavigateTo("/customers");
}

The code to the delete is mocked and returns true. When I unit test the cancel button it works but for the Delete button it does not give me the correct url

[Fact]
public void DeleteButtonClick()
{
    // ARRANGE
    var nav = _ctx.Services.GetRequiredService<NavigationManager>();
    var cut = _ctx.RenderComponent<CustomerDelete>(parameters =>
        parameters.Add(p => p.Id, 1));

    // ACT
    cut.Find("#Delete_Cust").Click();

    // Assert
    nav.Uri.Should().Be("http://localhost/customers"); // RETURNS http://localhost/
}

[Fact]
public void CancelClick()
{
    var nav = _ctx.Services.GetRequiredService<NavigationManager>();
    var cut = _ctx.RenderComponent<CustomerDelete>(parameters =>
        parameters.Add(p => p.Id, 1));

    cut.Find("#Cancel_Btn").Click();

    nav.Uri.Should().Be("http://localhost/customers"); // RETURNS CORRECT 
}

The Delete Test fails with the following

Expected nav.Uri to be "http://localhost/customers" but was "http://localhost/"

1 Answers

Make your [Fact] an async Task method and await the Click:

// ACT
//cut.Find("#Delete_Cust").Click();
await cut.Find("#Delete_Cust").ClickAsync(new MouseEventArgs());
Related