[英]How to test interaction with JS on a Blazor component using bUnit or any other?
[英]How to inject NavigationManager in bunit Blazor component unit test
從單元測試注入時出現此錯誤。
System.InvalidOperationException: ''NavigationManagerProxy' has not been initialized.'
我的代碼:
Services.AddSingleton<NavigationManager>(Mock.Of<NavigationManager>());
我將這個類用於我的單元測試:
internal class TestNav : NavigationManager
{
public TestNav()
{
Initialize("https://unit-test.example/", "https://unit-test.example/");
}
protected override void NavigateToCore(string uri, bool forceLoad)
{
NotifyLocationChanged(false);
}
}
然后在測試中設置如下:
Services.AddSingleton<NavigationManager>(new TestNav());
在為Blazing Pizza Workshop編寫測試時,我們使用了這個(類似於@Akinzekeel 的代碼):
public class FakeNavigationManager : NavigationManager
{
private readonly ITestRenderer renderer;
public FakeNavigationManager(ITestRenderer renderer)
{
Initialize("http://localhost/", "http://localhost/");
this.renderer = renderer;
}
protected override void NavigateToCore(string uri, bool forceLoad)
{
Uri = ToAbsoluteUri(uri).ToString();
renderer.Dispatcher.InvokeAsync(
() => NotifyLocationChanged(isInterceptedLink: false));
}
}
測試如下所示:
@inherits TestContext
@code {
private NavigationManager navigationManager;
public MainLayoutTests()
{
Services.AddSingleton<NavigationManager, FakeNavigationManager>();
navigationManager = Services.GetService<NavigationManager>();
}
[Fact]
public void MyOrdersNavigationItem_Is_Marked_As_Active_When_Viewing_MyOrdersPage()
{
var cut = Render(@<MainLayout />);
navigationManager.NavigateTo("myorders");
cut.Find("a[href=myorders]")
.ClassList
.Should()
.Contain("active");
}
}
我還沒有測試過各種場景,但這至少在這種情況下似乎有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.