Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ All notable changes to **bUnit** will be documented in this file. The project ad

## [Unreleased]

## Added
- Added `FindByAllByLabel` to `bunit.web.query` package. By [@linkdotnet](https://github.com/linkdotnet).

## [2.1.1] - 2025-11-21

### Changed
Expand Down
44 changes: 44 additions & 0 deletions src/bunit.web.query/Labels/LabelQueryExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using AngleSharp.Dom;
using Bunit.Labels.Strategies;
using Bunit.Web.AngleSharp;

namespace Bunit;

Expand Down Expand Up @@ -35,6 +36,25 @@ public static IElement FindByLabelText(this IRenderedComponent<IComponent> rende
return FindByLabelTextInternal(renderedComponent, labelText, options) ?? throw new LabelNotFoundException(labelText);
}

/// <summary>
/// Returns all elements (i.e. input, select, textarea, etc. elements) associated with the given label text.
/// </summary>
/// <param name="renderedComponent">The rendered fragment to search.</param>
/// <param name="labelText">The text of the label to search (i.e. the InnerText of the Label, such as "First Name" for a `<label>First Name</label>`)</param>
/// <param name="configureOptions">Method used to override the default behavior of FindAllByLabelText.</param>
/// <returns>A read-only collection of elements matching the label text. Returns an empty collection if no matches are found.</returns>
public static IReadOnlyList<IElement> FindAllByLabelText(this IRenderedComponent<IComponent> renderedComponent, string labelText, Action<ByLabelTextOptions>? configureOptions = null)
{
var options = ByLabelTextOptions.Default;
if (configureOptions is not null)
{
options = options with { };
configureOptions.Invoke(options);
}

return FindAllByLabelTextInternal(renderedComponent, labelText, options);
}

internal static IElement? FindByLabelTextInternal(this IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
{
foreach (var strategy in LabelTextQueryStrategies)
Expand All @@ -47,4 +67,28 @@ public static IElement FindByLabelText(this IRenderedComponent<IComponent> rende

return null;
}

internal static IReadOnlyList<IElement> FindAllByLabelTextInternal(this IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
{
var results = new List<IElement>();

foreach (var strategy in LabelTextQueryStrategies)
{
results.AddRange(strategy.FindElements(renderedComponent, labelText, options));
}

var seen = new HashSet<IElement>();
var distinctResults = new List<IElement>();

foreach (var element in results)
{
var underlyingElement = element.Unwrap();
if (seen.Add(underlyingElement))
{
distinctResults.Add(element);
}
}

return distinctResults;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@ namespace Bunit.Labels.Strategies;

internal interface ILabelTextQueryStrategy
{
IElement? FindElement(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options);
IElement? FindElement(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@scottsauber in the spirit of the testing-library: Should we not throw even an exception if there is more than one element? I kept it as is, but checking https://testing-library.com/docs/dom-testing-library/cheatsheet/#queries "findBy" throws if 1+ match was found

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our "normal" cut.Find also would return the first occurrence (regardless if we have more than 1 match)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So let's keep it, even if it "breaks" with the testing-library.

we can also change that in the future.

=> FindElements(renderedComponent, labelText, options).FirstOrDefault();

IEnumerable<IElement> FindElements(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Bunit.Labels.Strategies;

internal sealed class LabelTextUsingAriaLabelStrategy : ILabelTextQueryStrategy
{
public IElement? FindElement(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
public IEnumerable<IElement> FindElements(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
{
var caseSensitivityQualifier = options.ComparisonType switch
{
Expand All @@ -15,11 +15,11 @@ internal sealed class LabelTextUsingAriaLabelStrategy : ILabelTextQueryStrategy
_ => ""
};

var element = renderedComponent.Nodes.TryQuerySelector($"[aria-label='{labelText}'{caseSensitivityQualifier}]");
var elements = renderedComponent.Nodes.TryQuerySelectorAll($"[aria-label='{labelText}'{caseSensitivityQualifier}]");

if (element is null)
return null;

return element.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
foreach (var element in elements)
{
yield return element.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,15 @@ namespace Bunit.Labels.Strategies;

internal sealed class LabelTextUsingAriaLabelledByStrategy : ILabelTextQueryStrategy
{
public IElement? FindElement(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
public IEnumerable<IElement> FindElements(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
{
var elementsWithAriaLabelledBy = renderedComponent.Nodes.TryQuerySelectorAll("[aria-labelledby]");

foreach (var element in elementsWithAriaLabelledBy)
{
var labelElement = renderedComponent.Nodes.TryQuerySelector($"#{element.GetAttribute("aria-labelledby")}");
if (labelElement is not null && labelElement.GetInnerText().Equals(labelText, options.ComparisonType))
return element.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
yield return element.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
}

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@ namespace Bunit.Labels.Strategies;

internal sealed class LabelTextUsingForAttributeStrategy : ILabelTextQueryStrategy
{
public IElement? FindElement(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
public IEnumerable<IElement> FindElements(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
{
var matchingLabel = renderedComponent.Nodes.TryQuerySelectorAll("label")
.SingleOrDefault(l => l.TextContent.Trim().Equals(labelText, options.ComparisonType));
var matchingLabels = renderedComponent.Nodes.TryQuerySelectorAll("label")
.Where(l => l.TextContent.Trim().Equals(labelText, options.ComparisonType));

if (matchingLabel is null)
return null;
foreach (var matchingLabel in matchingLabels)
{
var forAttribute = matchingLabel.GetAttribute("for");
if (string.IsNullOrEmpty(forAttribute))
continue;

var matchingElement = renderedComponent.Nodes.TryQuerySelector($"#{matchingLabel.GetAttribute("for")}");

if (matchingElement is null)
return null;

return matchingElement.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
var matchingElement = renderedComponent.Nodes.TryQuerySelector($"#{forAttribute}");
if (matchingElement is not null)
yield return matchingElement.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@ namespace Bunit.Labels.Strategies;

internal sealed class LabelTextUsingWrappedElementStrategy : ILabelTextQueryStrategy
{
public IElement? FindElement(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
public IEnumerable<IElement> FindElements(IRenderedComponent<IComponent> renderedComponent, string labelText, ByLabelTextOptions options)
{
var matchingLabel = renderedComponent.Nodes.TryQuerySelectorAll("label")
.SingleOrDefault(l => l.GetInnerText().Trim().StartsWith(labelText, options.ComparisonType));
var matchingLabels = renderedComponent.Nodes.TryQuerySelectorAll("label")
.Where(l => l.GetInnerText().Trim().StartsWith(labelText, options.ComparisonType));

var matchingElement = matchingLabel?
.Children
.SingleOrDefault(n => n.IsHtmlElementThatCanHaveALabel());

return matchingElement?.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
foreach (var matchingLabel in matchingLabels)
{
var matchingElements = matchingLabel.Children.Where(n => n.IsHtmlElementThatCanHaveALabel());
foreach (var matchingElement in matchingElements)
{
yield return matchingElement.WrapUsing(new ByLabelTextElementFactory(renderedComponent, labelText, options));
}
}
}
}
1 change: 1 addition & 0 deletions src/bunit/InternalsVisibleTo.cs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bunit.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001be6b1a2ca57b09b7040e2ab0993e515296ae22aef4031a4fe388a1336fe21f69c7e8610e9935de6ed18d94b5c98429f99ef62ce3d0af28a7088f856239368ea808ad4c448aa2a8075ed581f989f36ed0d0b8b1cfcaf1ff6a4506c8a99b7024b6eb56996d08e3c9c1cf5db59bff96fcc63ccad155ef7fc63aab6a69862437b6")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bunit.Web.Query, PublicKey=002400000480000094000000060200000024000052534131000400000100010001be6b1a2ca57b09b7040e2ab0993e515296ae22aef4031a4fe388a1336fe21f69c7e8610e9935de6ed18d94b5c98429f99ef62ce3d0af28a7088f856239368ea808ad4c448aa2a8075ed581f989f36ed0d0b8b1cfcaf1ff6a4506c8a99b7024b6eb56996d08e3c9c1cf5db59bff96fcc63ccad155ef7fc63aab6a69862437b6")]
142 changes: 142 additions & 0 deletions tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -351,4 +351,146 @@ public void Test021(string htmlElementWithLabel)
input.NodeName.ShouldBe(htmlElementWithLabel, StringCompareShould.IgnoreCase);
input.Id.ShouldBe($"{htmlElementWithLabel}-with-label");
}

[Fact(DisplayName = "FindAllByLabelText should return empty collection when no elements match")]
public void Test100()
{
var cut = Render<Wrapper>(ps =>
ps.AddChildContent("<div>No labels here</div>"));

var elements = cut.FindAllByLabelText("Non-existent label");

elements.ShouldBeEmpty();
}

[Fact(DisplayName = "FindAllByLabelText should return multiple elements with same label text using for attribute")]
public void Test101()
{
var labelText = "Same Label";
var cut = Render<Wrapper>(ps =>
ps.AddChildContent($"""
<label for="input-1">{labelText}</label>
<input id="input-1" />
<label for="input-2">{labelText}</label>
<input id="input-2" />
"""));

var elements = cut.FindAllByLabelText(labelText);

elements.Count.ShouldBe(2);
elements[0].Id.ShouldBe("input-1");
elements[1].Id.ShouldBe("input-2");
}

[Fact(DisplayName = "FindAllByLabelText should return multiple elements with same aria-label")]
public void Test102()
{
var labelText = "Aria Label";
var cut = Render<Wrapper>(ps =>
ps.AddChildContent($"""
<input id="input-1" aria-label="{labelText}" />
<input id="input-2" aria-label="{labelText}" />
<button id="button-1" aria-label="{labelText}" />
"""));

var elements = cut.FindAllByLabelText(labelText);

elements.Count.ShouldBe(3);
elements[0].Id.ShouldBe("input-1");
elements[1].Id.ShouldBe("input-2");
elements[2].Id.ShouldBe("button-1");
}

[Fact(DisplayName = "FindAllByLabelText should return multiple elements wrapped in labels")]
public void Test103()
{
var labelText = "Wrapped Label";
var cut = Render<Wrapper>(ps =>
ps.AddChildContent($"""
<label>{labelText}<input id="input-1" /></label>
<label>{labelText}<input id="input-2" /></label>
"""));

var elements = cut.FindAllByLabelText(labelText);

elements.Count.ShouldBe(2);
elements[0].Id.ShouldBe("input-1");
elements[1].Id.ShouldBe("input-2");
}

[Fact(DisplayName = "FindAllByLabelText should return multiple elements using aria-labelledby")]
public void Test104()
{
var labelText = "Aria Labelled By";
var cut = Render<Wrapper>(ps =>
ps.AddChildContent($"""
<h2 id="heading-1">{labelText}</h2>
<input id="input-1" aria-labelledby="heading-1" />
<input id="input-2" aria-labelledby="heading-1" />
"""));

var elements = cut.FindAllByLabelText(labelText);

elements.Count.ShouldBe(2);
elements[0].Id.ShouldBe("input-1");
elements[1].Id.ShouldBe("input-2");
}

[Fact(DisplayName = "FindAllByLabelText should return elements from different strategies")]
public void Test105()
{
var labelText = "Mixed Label";
var cut = Render<Wrapper>(ps =>
ps.AddChildContent($"""
<label for="input-for">{labelText}</label>
<input id="input-for" />
<input id="input-aria" aria-label="{labelText}" />
<label>{labelText}<input id="input-wrapped" /></label>
<h2 id="heading-1">{labelText}</h2>
<input id="input-labelledby" aria-labelledby="heading-1" />
"""));

var elements = cut.FindAllByLabelText(labelText);

elements.Count.ShouldBe(4);
var ids = elements.Select(e => e.Id).ToList();
ids.ShouldContain("input-for");
ids.ShouldContain("input-aria");
ids.ShouldContain("input-wrapped");
ids.ShouldContain("input-labelledby");
}

[Fact(DisplayName = "FindAllByLabelText should deduplicate elements matched by multiple strategies")]
public void Test106()
{
var labelText = "Duplicate Label";
var cut = Render<Wrapper>(ps =>
ps.AddChildContent($"""
<label for="input-1">{labelText}</label>
<input id="input-1" aria-label="{labelText}" />
"""));

var elements = cut.FindAllByLabelText(labelText);

// The same input is matched by both 'for' attribute and 'aria-label' strategies
// but should only appear once in the result
elements.Count.ShouldBe(1);
elements[0].Id.ShouldBe("input-1");
}

[Fact(DisplayName = "FindAllByLabelText should respect case-insensitive comparison option")]
public void Test107()
{
var cut = Render<Wrapper>(ps =>
ps.AddChildContent("""
<label for="input-1">Label Text</label>
<input id="input-1" />
<label for="input-2">LABEL TEXT</label>
<input id="input-2" />
"""));

var elements = cut.FindAllByLabelText("label text", o => o.ComparisonType = StringComparison.OrdinalIgnoreCase);

elements.Count.ShouldBe(2);
}
}