Home > OS >  How can I access an input elements id or name from an AngleSharp.Dom.INode while bUnit testing?
How can I access an input elements id or name from an AngleSharp.Dom.INode while bUnit testing?

Time:05-12

I am attempting to test our Blazor project with bUnit and am having issues with a bUnit Assert.

This is the component I am trying to test:

<div>
foreach(KeyValuePair<String, String> entry in Dictionary<String, String>)
{
    <div >
        <input  type="radio" name="[email protected]" id="[email protected]@entry.Key" checked=@(firstOptionEnabled) @onclick="() => doSomethingAwesome = entry.Key">
        <label  for="[email protected]@entry.Key"> @entry.Value </label>
    </div>
    firstOptionEnabled = false;
}
</div>
@code
{
    [Parameter]
    public Document ChosenDocument { get; set; }
}

The test I have written looks like this:

[Fact]
public async void MyTest()
{
    var cut = RenderComponent<MyComponent ChosenDocument="documentToTest">();
    IRefreshableElementCollection<IElement> allElements = cut.FindAll("div [class=\"form-check\"]");
    // These are the <div > elements
    foreach(IElement element in allElements)
    {
        // These are the <input> elements
        foreach(INode node in element.ChildNodes)
        {
            // Here, I want to assert on data within each of these `INode` 
        }
    }
}

My problem is happening with the Assert I want to perform.

I want to assert the id or name of each of the input elements like so:

Assert.Equal(("myAwesomeName-"   ChosenDocument.docId), <something here ...>);

Where <something here ...> is either id or name of the input element. However, I cannot seem to get hold of the id or name from the component under test.

When I debug the test and look in the "Locals" window, I can see this:

- node {AngleSharp.Html.Dom.HtmlInputElement}   AngleSharp.Dom.INode {AngleSharp.Html.Dom.HtmlInputElement}
    // ...
    Id      "myAwesomeName-1234567890-text"    string
    // ...
    Name    "myAwesomeName-1234567890"         string
    // ...

So, it looks like those two pieces of information should be available to me within my Assert, but they are not; well, at least not evident to me.

How can I access those two pieces of data I need for my Assertion?

CodePudding user response:

Does something like this work? You should be able to grab all the input elements directly:

var inputs = cut.FindAll(".form-check-input");
foreach (var input in inputs)
{
    Assert.Equal($"myAwesomeName-{ChosenDocument.docId}", input.GetAttribute("name"));
}

or even more concise:

var inputs = cut.FindAll(".form-check-input");
Assert.All(inputs, i => Assert.Equal($"myAwesomeName-{ChosenDocument.docId}", i.GetAttribute("name")));
  • Related