为什么 bUnit 告诉我它不能"click"按钮,因为该元素没有用于 onclick 的事件处理程序,即使它有?



元素在.RAZOR页面中的样子:

<button id="@(theID)" type="button" class="btn btn-primary" onclick="window.open('https://www.google.com/');">Do Something</button>

我在bUnit test .CS文件中有这个语句:

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通过exportButton.MarkupMatches()测试,因为这是bUnit收到的标记中的内容:

<button id="abc123" type="button" class="btn btn-primary" onclick="window.open('https://www.google.com/');">Do Something</button>

然而,bUnit失败的是Click()。错误信息是这样的:

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)

从bUnit接收到的标记中可以清楚地看到:

<button id="abc123" type="button" class="btn btn-primary" onclick="window.open('https://www.google.com/');">Do Something</button>

确实有一个onclick事件需要处理。

那么为什么测试失败了?为什么bUnit说没有可处理事件,即使有。

您不是绑定到c#事件处理程序,而是绑定到JavaScript事件处理程序。bUnit只能触发c#事件处理程序,也就是。以@开头的,例如@onclick

这是因为bUnit不运行JavaScript,所以你不能用它在你的HTML中测试在线JavaScript。将JavaScript放入.js文件中的函数中,并使用Jsinterop调用它。然后,您可以使用bUnit的JSInterop实现来验证函数是否被调用。

更多信息在这里:https://bunit.dev/docs/test-doubles/emulating-ijsruntime.html