Clicking an Anchor Tag does not update NavigationManager
japhelps opened this issue · 2 comments
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:
- bUnit version: 1.28.9
- .NET Runtime and Blazor version: 8
- OS type and version: Win11
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.
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.