簡體   English   中英

如何使用 bUnit 或任何其他組件在 Blazor 組件上測試與 JS 的交互?

[英]How to test interaction with JS on a Blazor component using bUnit or any other?

有一個 Blazor 組件通過JSRuntime與 JS 交互,並通過dotNetObjectRef從 JS 返回。

該組件有一個 OnInit 事件,該事件由 JS 使用dotNetObjectRef.invokeMethodAsync("handler")調用。 它是通過調用 JS addEventListener方法從 DotNet 端配置的。

該組件可以工作,但是,在使用 bUnit 進行測試期間,JS 代碼根本不會運行。 如何使測試這個組件成為可能。

使用 bUnit 測試代碼:

    [Fact]
    public async Task Events_ThatEventIsRaised()
    {
        bool isEventRaised = false;

        // Arrange
        using var context = CreateContext();
 
        // Act
        var myComponent = context.RenderComponent<MyComponent>(parameters => parameters
                .Add(p => p.OnInit, e => isEventRaised = true) 
            );

        // Assert
        Assert.True(isEventRaised); 
    }

我嘗試手動加載 JS 文件,但沒有成功:

context.JSInterop.SetupModule("component.js");

bUnit 包含 Blazors JSInterop 的假實現。 它的工作方式與 Moq 非常相似,允許您設置對 JavaScript 的預期調用並指定響應。 在此處了解更多信息: https://bunit.dev/docs/test-doubles/emulating-ijsruntime

要在 Blazor 組件中模擬 JavaScript 調用方法,只需自己調用這些方法,例如:

[Fact]
public async Task Events_ThatEventIsRaised()
{
    bool isEventRaised = false;

    // Arrange
    using var context = CreateContext();
    var myComponent = context.RenderComponent<MyComponent>(parameters => parameters
            .Add(p => p.OnInit, e => isEventRaised = true) 
        );

    // Act
    myComponent.Instance.Handler();

    // Assert
    Assert.True(isEventRaised); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM