如何使用 bUnit 检查元素是否获得焦点?

问题描述 投票:0回答:1

假设我有一个 Blazor 组件

<MyButton/>
,为了简单起见,它是这样实现的:

<button>MyButton</button>

我使用 bUnit 对我的组件进行单元测试,如下所示:

@inherits TestContext

@code {
    [Fact]
    public void MyButton_Focuses_Correctly()
    {
        IRenderedFragment cut = Render(@<MyButton></MyButton>);
        IElement button = cut.Find("button");

        button.Click();

        Assert.True(button.IsFocused); // <- does not work for some reason
    }
}

对于

IsDisabled
IsChecked
等类似的东西,我可以查看 DOM 属性,但我不能将这种解决方法与
IsFocused
一起使用,因为不存在 HTML-
focused
属性之类的东西。

Assert.True(button.HasAttribute("disabled"));
.net unit-testing blazor xunit bunit
1个回答
0
投票

您可以在按钮单击时调用js方法,并在document.activeElement是否为当前按钮的组件上设置隐藏字段或元素。

await JS.InvokeAsync<boo>("hasFocus", button);

hasFocus 就在哪里

function hasFocus(button) {
  document.getElementById("isButtonFocus").value = (button === document.activeElement);
}

在您的bunit测试中,您可以找到并检查隐藏字段的值

// write code to find and check the value of hidden field
cut.Find("#isButtonFocus").value;
© www.soinside.com 2019 - 2024. All rights reserved.