这是它在 .RAZOR
页面中显示的元素:
<button id="@(theID)" type="button" class="btn btn-primary" onclick="window.open('https://www.google.com/');">Do Something</button>
我在 bUnit 测试 .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 说没有可处理的事件,即使有。
回答1
您不是绑定到 C# 事件处理程序,而是绑定到 JavaScript 事件处理程序。 bUnit 只能触发 C# 事件处理程序,也就是。以 @
开头的那些,例如@onclick
。
这是因为 bUnit 不运行 JavaScript,所以你不能用它来测试你的 HTML 中的在线 JavaScript。将您的 JavaScript 放入 .js 文件中的函数中,然后由 Jsinterop 调用它。然后你可以使用 bUnit 的 JSInterop 实现来验证函数是否被调用。
更多相关信息:https://bunit.dev/docs/test-doubles/emulating-ijsruntime.html