Triggering Event Handlers in Components
Blazor makes it possible to bind many event handlers to elements in a Blazor component using the @onXXXX
syntax, e.g. @onclick="MyClickHandler"
.
bUnit comes with event dispatch helper methods that makes it possible to invoke event handlers for all event types supported by Blazor.
The built-in dispatch event helpers are:
- Clipboard events
- Drag events
- Focus events
- General events
- Input events
- Keyboard events
- Media events
- Mouse events
- Pointer events
- Progress events
- Touch event
To use these, first find the element in the component under test where the event handler is bound. This is usually done with the Find(string cssSelector)
method. Next, invoke the event dispatch helper method of choice.
The following section demonstrates how to do this...
Invoking an Event Handler on an Element
To invoke an event handler on an element, first find the element in the component under test, and then call the desired event dispatch helper method.
Let's look at a common example where an @onclick
event handler is invoked. The example will use the <ClickMe>
component listed here:
<button @onclick="ClickHandler">Click ME!</button>
@code
{
void ClickHandler(MouseEventArgs args)
{
// ...
}
}
To trigger the @onclick
ClickHandler
event handler method in the <ClickMe>
component, do the following:
// Arrange
using var ctx = new TestContext();
var cut = ctx.RenderComponent<ClickMe>();
var buttonElement = cut.Find("button");
// Act
buttonElement.Click();
buttonElement.Click(detail: 3, ctrlKey: true);
buttonElement.Click(new MouseEventArgs());
// Assert
// ...
This is what happens in the test:
- In the arrange step of the test, the
<ClickMe>
component is rendered and the<button>
element is found using theFind(string cssSelector)
method. - The act step of the test is the
<button>
's click event handler. In this case, theClickHandler
event handler method is invoked in three different ways:- The first and second invocation uses the same
Click
method. It has a number of optional arguments, some of which are passed in the second invocation. If any arguments are provided, they are added to an instance of theMouseEventArgs
type, which is passed to the event handler if it has it as an argument. - The last invocation uses the
Click
method that takes an instance of theMouseEventArgs
type, which is passed to the event handler if it has it as an argument.
- The first and second invocation uses the same
All the event dispatch helper methods have the same two overloads: one that takes a number of optional arguments, and one that takes one of the EventArgs
types provided by Blazor.