Stevie
Stevie

Reputation: 463

Unit test subdivs with bUnit

I am trying to test a blazor component. In the logic of the component i set some text in an subdiv somewhere inside the component. Now i want to verify that the text is set properly:

<div>
    <div>
    </div>
    <div>
        @Title
    </div>
</div>

At the moment i use the following code to instantiate the component. Now i want to verify that "title" is actually used as the title.

[Fact]
public void TestSomething()
{
    // act
    var cut = RenderComponent<MyComponent>(parameters => parameters
        .Add(p => p.Title, "title")
    );
}

Now how would i verify that "title" is actually rendered in the right place?

I found two approaches: either i build an system to generate unique ids throughout my whole project or i just set static ids. Both are either way to much work or end in duplicate ids. Are there any better approaches to test something like this?

Upvotes: 0

Views: 184

Answers (2)

Link
Link

Reputation: 1711

There is another way if you are not willing to add id's or classes. The CSS specification introduced a bunch of pseudo selectors, one of them is the contains selector.

So you could do something like this to make your test somewhat work:

[Fact]
public void ShouldRenderDiv()
{
    var cut = Render<MyComponent>(ps => ps.Add(p => p.Title, "Foo"));

    var theDiv = cut.Find("""div > div:contains("Foo")""");

    theDiv.TextContent.Should().Be("Foo");
}

Now, the downside of this approach is that your test is tightly coupled to the markup of your component under test.

Upvotes: 0

Stevie
Stevie

Reputation: 463

Figured it out myself: i just use a custom data attribute, e.g. data-id-abcd I can reference this in bUnit using the following CSS selector: [data-id-abcd].

For every tag i want to access i create a custom attribute with some random 4-digit hex id. Using this technique i can identify tags without having some duplicate ids. Further it keeps the code pretty clean and maintainable as it only adds a hand full of attributes to every component.

Upvotes: 0

Related Questions