Skip to content

Commit 4717a1b

Browse files
committed
feat: support for all element types that can have a wrapped label
1 parent 7d031df commit 4717a1b

File tree

4 files changed

+28
-8
lines changed

4 files changed

+28
-8
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
namespace Bunit;
2+
3+
internal class LabelQueryConstants
4+
{
5+
internal static readonly List<string> HtmlElementsThatCanHaveALabel = new()
6+
{
7+
"input",
8+
"select",
9+
"textarea",
10+
"button",
11+
"meter",
12+
"output",
13+
"progress",
14+
};
15+
}

src/bunit.web.query/Labels/Strategies/LabelTextUsingWrappedElementStrategy.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,6 @@ internal class LabelTextUsingWrappedElementStrategy : ILabelTextQueryStrategy
1111

1212
return matchingLabel?
1313
.Children
14-
.SingleOrDefault(n => n.NodeName == "INPUT");
14+
.SingleOrDefault(n => LabelQueryConstants.HtmlElementsThatCanHaveALabel.Contains(n.NodeName, StringComparer.OrdinalIgnoreCase));
1515
}
1616
}

tests/bunit.testassets/BlazorE2E/LabelQueryComponent.razor

+6-3
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,12 @@
1010
<input id="ignored-input"/>
1111

1212
@* Testing wrapped label *@
13-
<label>Wrapped Label
14-
<input id="wrapped-label"/>
15-
</label>
13+
@foreach (var htmlElement in htmlElementsThatCanHaveALabel)
14+
{
15+
<label>@htmlElement Wrapped Label
16+
@((MarkupString) $"""<{htmlElement} id="{htmlElement}-wrapped-label"></{htmlElement}>""")
17+
</label>
18+
}
1619

1720
@* Testing no input *@
1821
<label>Label With Missing Input</label>

tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs

+6-4
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,17 @@ public void Test002()
3838
.CssSelector.ShouldBe(expectedLabelText);
3939
}
4040

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

46-
var input = cut.FindByLabelText("Wrapped Label");
47+
var input = cut.FindByLabelText($"{htmlElementWithLabel} Wrapped Label");
4748

4849
input.ShouldNotBeNull();
49-
input.Id.ShouldBe("wrapped-label");
50+
input.NodeName.ShouldBe(htmlElementWithLabel, StringCompareShould.IgnoreCase);
51+
input.Id.ShouldBe($"{htmlElementWithLabel}-wrapped-label");
5052
}
5153

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

0 commit comments

Comments
 (0)