'Why is bUnit telling me it cannot "click" a button because the element does not have an event handler for onclick, even though it does?
This is the element as it looks in its .RAZOR page:
<button id="@(theID)" type="button" class="btn btn-primary" onclick="window.open('https://www.google.com/');">Do Something</button>
I have this statement in the bUnit test .CS file:
IElement theButton = cut.Find("button[id=\"" + theID + "\"]");
exportButton.MarkupMatches("<button id=\"" + theID + "\" type=\"button\" class=\"btn btn-primary\" onclick=\"window.open('https://www.google.com/');\">Do Something</button>");
exportButton.Click();
bUnit passes the exportButton.MarkupMatches() test as this is what is in the markup bUnit receives:
<button id="abc123" type="button" class="btn btn-primary" onclick="window.open('https://www.google.com/');">Do Something</button>
However, it's the Click() that bUnit is failing on. The error message is this:
My.Domain.Tests.TestTheThing
Source: MyAwesomeTest.razor line N
Duration: 485 ms
Message:
Bunit.MissingEventHandlerException : The element does not have an event handler for the event 'onclick', nor any other events.
Stack Trace:
TriggerEventDispatchExtensions.TriggerBubblingEventAsync(ITestRenderer renderer, IElement element, String eventName, EventArgs eventArgs) line 102
TriggerEventDispatchExtensions.TriggerEventAsync(IElement element, String eventName, EventArgs eventArgs) line 76
MouseEventDispatchExtensions.ClickAsync(IElement element, MouseEventArgs eventArgs) line 373
MouseEventDispatchExtensions.Click(IElement element, Int64 detail, Double screenX, Double screenY, Double clientX, Double clientY, Double offsetX, Double offsetY, Int64 button, Int64 buttons, Boolean ctrlKey, Boolean shiftKey, Boolean altKey, Boolean metaKey, String type) line 322
MyAwesomeTest.TestTheThing() line N
<>c.<ThrowAsync>b__140_0(Object state)
As can be clearly seen in the markup bUnit receives:
<button id="abc123" type="button" class="btn btn-primary" onclick="window.open('https://www.google.com/');">Do Something</button>
There is, indeed an onclick event to handle.
So why is the test failing? Why is bUnit saying there is not a handleable event even though there is.
Solution 1:[1]
You are not binding to a C# event handler, but to a JavaScript one. bUnit can only trigger C# event handlers, aka. the ones that start with an @, e.g. @onclick.
This is because bUnit does not run JavaScript, so you cannot use it to test online JavaScript in your HTML like that. Put your JavaScript into a function in .js file, and Jsinterop to call it. Then you can use bUnit's implementation of JSInterop to verify that the function was called.
More about that here: https://bunit.dev/docs/test-doubles/emulating-ijsruntime.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Egil Hansen |
