Test that a Blazor EventCallback is called

102 views Asked by At

If I have a Blazor component:

@code {
    [Parameter] public EventCallback<string> OnEvent { get; set; }
}

And a bUnit test:

@code {
    var cut = RenderComponent<MyComp>(builder =>
    { 
        builder.Add(mc => mc.OnEvent, Handler("Fired"));
    }

    await cut.Instance.OnEvent.InvokeAsync();

    private void Handler(string val) {}
}

Two questions:

  1. Can I convert this to use an arbitrary method defined and setup using Moq?

I have tried:

Mock<EventHandler<string>> mockHandler = new Mock<EventHandler<string>>();
mockHandler.Setup(m => m.X(It.IsAny<object>(), "Fired"));

But I can't figure out how to pass the mockHandler method to the component.

  1. How can I verify that OnEvent is fired?
1

There are 1 answers

0
Egil Hansen On BEST ANSWER

Dont call EventCallbacks directly in your tests, trigger them as you would through a user interaction.

E.g. to test the EventCallback in the following component:

<button @onclick="Clicked">Click Me</button> 
@code {
    [Parameter] public EventCallback Clicked { get; set; }
}

Do this:

  [Fact]
  public void TestClickTriggered() 
  {
    var called = false;
    var cut = RenderComponent<MyComp>(builder =>
    { 
        // Pass an inline lambda that updates `called` variable
        builder.Add(mc => mc.Clicked, val => called = true);
    }

    // Find the button and trigger the onclick eventhandler, 
    // simulating a user clicking a button in the browser.
    cut.Find("button").Click();

    Assert.True(called);
  }

Learn more over on https://bunit.dev/docs/getting-started