Search code examples
c#unit-testingbunit

Check if Element is focused - Blazor B-Unit


I am writing unittests for my component. This component looks like this:

component.razor
<div class="main-data-data-row" @onclick="@HandleDataRowClick">
   ...
   <input class="main-data-data-row__chip-container__input" ref="InputRef"/>
</div>
component.razor.cs
public partial class DataRowTagSelectComponent<T> : DataRowComponentBase
{
   ...

   public ElementReference InputRef { get; set; }
   
   ...

   public void HandleDataRowClick()
   {
      if (!Disabled)
      {
         InputRef.FocusAsync();
      }
   }
}

Now to the question

As you can see, on click of the container, the input field is focused. How would one test this in a B-Unit test?

This is how my unit test looks so far:

[Fact]
public void ClickComponent_FocusInputField()
{
   string testIdentifier = "MyTestIdentifier";
   List<string> testValue = new() { "MyTestValue1", "MyTestValue3", "MyTestValue3", };

   using var ctx = new TestContext();

   var cut = ctx.RenderComponent<DataRowTagSelectComponent<string>>(parameters => parameters
         .Add(p => p.Values, testValue)
         .Add(p => p.DataRowIdentifier, testIdentifier)
         .Add(p => p.MainDataEditMode, true)
         );

   IElement mainContainerTarget = cut.Find(".main-data-data-row");

   //mocking click of container
   mainContainerTarget.Click();

   // important stuff is happening here - how do i access the currently active item?
   // or how do i check if a element is focused?
   IElement inputTarget = cut.Find(".main-data-data-row__chip-container__input");
   Assert.NotNull(inputTarget);
        
   Assert.Equal(inputTarget, ???)
}

Solution

  • IElement has an IsFocused property that you can use as follows:

    IElement inputTarget = cut.Find(".main-data-data-row__chip-container__input");
    Assert.True(inputTarget.IsFocused);