bUnit-dev / bUnit

bUnit is a testing library for Blazor components that make tests look, feel, and runs like regular unit tests. bUnit makes it easy to render and control a component under test’s life-cycle, pass parameter and inject services into it, trigger event handlers, and verify the rendered markup from the component using a built-in semantic HTML comparer.
https://bunit.dev
MIT License
1.11k stars 104 forks source link

Clicking an Anchor Tag does not update NavigationManager #1468

Closed japhelps closed 2 months ago

japhelps commented 2 months ago

If using an anchor tag for navigation, the only way I have found to click the link is to use AngleSharp.IHtmlElement.DoClick(). This method does not cause the bUnit fake NavigationManager to update with the URL from the anchor tag.

Example: Testing this component:

@page "/"

<a href="/myotherpage">Click Here</a>

With this test:

using AngleSharp.Html.Dom;
using Bunit;
using Microsoft.AspNetCore.Components;

namespace MyNamespace;

public class MyPageTests : TestContext
{
    [Fact]
    public void CanNavigateToMyOtherPage()
    {
        var navigationManager = Services.GetRequiredService<NavigationManager>();
        var cut = RenderComponent<MyPage>();

        var link = cut.Find("a");
        ((IHtmlElement)link).DoClick();

        cut.WaitForAssertion(() => Assert.Equal("/myotherpage", new Uri(navigationManager.Uri).AbsolutePath));
    }
}

Results in this output:

Assert.Equal() Failure: Strings differ
            ↓ (pos 1)
Expected: "/myotherpage"
Actual:   "/"

Expected behavior:

Version info:

linkdotnet commented 2 months ago

Hey @japhelps,

basically your scenario doesn't work by design. bUnit is not a real browser in the sense that when you click in navigates somewhere. Bunit doesn't have a router to such things. When you call Click you basically "just" invoke the @onclick event handler of the element in question.

From a unit testing point of view, clicking on the <a> element, which opens a new tab with the given URL, is a 3rd party concern. You can and should rely on the fact that Blazor and your browser do the right things.

The mindset with bUnit - and unit testing in general - is that you concentrate on your (business) logic.

japhelps commented 2 months ago

Thank you for the information! I had already guessed the technical reasons why it wasn't working. I just wasn't sure if this was an oversight or not as I have not found any information on StackOverflow or the bUnit documentation on <a> tag use.