Skip to content

Commit

Permalink
feat: support for all element types that can have a wrapped label
Browse files Browse the repository at this point in the history
  • Loading branch information
scottsauber committed Nov 1, 2023
1 parent 7d031df commit 120227d
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 8 deletions.
15 changes: 15 additions & 0 deletions src/bunit.web.query/Labels/LabelQueryConstants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Bunit;

internal class LabelQueryConstants
{
internal static readonly List<string> HtmlElementsThatCanHaveALabel = new()
{
"input",
"select",
"textarea",
"button",
"meter",
"output",
"progress",
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ internal class LabelTextUsingWrappedElementStrategy : ILabelTextQueryStrategy

return matchingLabel?
.Children
.SingleOrDefault(n => n.NodeName == "INPUT");
.SingleOrDefault(n => LabelQueryConstants.HtmlElementsThatCanHaveALabel.Contains(n.NodeName, StringComparer.OrdinalIgnoreCase));
}
}
9 changes: 6 additions & 3 deletions tests/bunit.testassets/BlazorE2E/LabelQueryComponent.razor
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@
<input id="ignored-input"/>

@* Testing wrapped label *@
<label>Wrapped Label
<input id="wrapped-label"/>
</label>
@foreach (var htmlElement in htmlElementsThatCanHaveALabel)
{
<label>@htmlElement Wrapped Label
@((MarkupString) $"""<{htmlElement} id="{htmlElement}-wrapped-label"></{htmlElement}>""")
</label>
}

@* Testing no input *@
<label>Label With Missing Input</label>
Expand Down
10 changes: 6 additions & 4 deletions tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,17 @@ public void Test002()
.CssSelector.ShouldBe(expectedLabelText);
}

[Fact(DisplayName = "Should return back input associated with label when label when is wrapped around input")]
public void Test003()
[Theory(DisplayName = "Should return back element associated with label when label when is wrapped around element")]
[MemberData(nameof(HtmlElementsThatCanHaveALabel))]
public void Test003(string htmlElementWithLabel)
{
var cut = RenderComponent<LabelQueryComponent>();

var input = cut.FindByLabelText("Wrapped Label");
var input = cut.FindByLabelText($"{htmlElementWithLabel} Wrapped Label");

input.ShouldNotBeNull();
input.Id.ShouldBe("wrapped-label");
input.NodeName.ShouldBe(htmlElementWithLabel, StringCompareShould.IgnoreCase);
input.Id.ShouldBe($"{htmlElementWithLabel}-wrapped-label");
}

[Fact(DisplayName = "Should throw exception when label text exists but is not tied to any input")]
Expand Down

0 comments on commit 120227d

Please sign in to comment.