使用 bUnit 测试 Blazor 组件中 InputFile 的事件处理程序

Test event handler of InputFile in Blazor component with bUnit

我有一个这样的 Blazor 组件:

// MyComponent.razor

<InputFile id="input-file" OnChange="@LoadImage" accept=".jpg,.jpeg,.png"/>

@code {
    internal IBrowserFile? File;

    private void LoadImage(InputFileChangeEventArgs args) => File = args.File;
}

我想通过以下测试使用 bUnit 测试此组件的事件处理程序:

[Test]
public void UploadFile()
{
    // Arrange
    var browserFile = new Mock<IBrowserFile>().Object;
    var ctx = new TestContext();
    var testee = ctx.RenderComponent<MyComponent>

    // Act
    testee.Find("[id^=\"input-file\"]").Change(new InputFileChangeEventArgs(new []{browserFile}));

    // Assert
    testee.Instance.File.Should().Be(browserFile);
}

此测试失败并出现以下错误:

Bunit.MissingEventHandlerException : The element does not have an event handler for the event 'onchange', nor any other events.
   at Bunit.TriggerEventDispatchExtensions.TriggerNonBubblingEventAsync(ITestRenderer renderer, IElement element, String eventName, EventArgs eventArgs) in /_/src/bunit.web/EventDispatchExtensions/TriggerEventDispatchExtensions.cs:line 144
   at Bunit.InputEventDispatchExtensions.ChangeAsync(IElement element, ChangeEventArgs eventArgs) in /_/src/bunit.web/EventDispatchExtensions/InputEventDispatchExtensions.cs:line 36
   at Bunit.InputEventDispatchExtensions.Change[T](IElement element, T value) in /_/src/bunit.web/EventDispatchExtensions/InputEventDispatchExtensions.cs:line 18

那么如何触发 Blazor 的 OnChange 事件 InputFile

谢谢!

Testing components that uses the component 讨论中有完整记录,在组件上调用 OnChange。在您的代码中:

var testee = ctx.RenderComponent<MyComponent>();

var filesToUpload = new InputFileChangeEventArgs(new []{browserFile});
var inputComponent = testee.FindComponent<InputFile>().Instance;

// Invoke the OnChange event callback to emulate the
// user uploading one or more files
await cut.InvokeAsync(() => 
    inputComponent.OnChange.InvokeAsync(filesToUpload));

// ...

重要部分:

要使用 InputFile,您必须设置 JSInterop。使用 TestContext class 来手动创建上下文(避免这种情况:ctx = new TestContext();):

    public class FileUpload1Test : TestContext
    {
        public FileUpload1Test()
        {
            // FileInput component configuration
            Services.AddSingleton(Options.Create(new RemoteBrowserFileStreamOptions()));
            JSInterop.SetupVoid(invocation => invocation.Identifier == "Blazor._internal.InputFile.init")
                .SetVoidResult();
        }