Skip to content

Commit

Permalink
feat: Add FindByLabelText to find elements by the text of their labels (
Browse files Browse the repository at this point in the history
#1252)

* add label, aria-label, wrapped label

* switch to strategy pattern

* feat: support for all element types that can have a label

* feat: support for all element types that can have a wrapped label

* feat: support for all element types that can have an aria-label

* feat: support for all element types that can have an aria-labelledby

* style: remove comment

* fix: use theorydata

* fix: use method instead of list

* failing test to prove the re-rendered element issue

* move to element factory to prevent re-renders causing issues

* fix: switch to array for strategies

* fix: remove todos

* fix: move to new ielementwrapperfactory

* fix: use custom labelnotfoundexception

* feat: support for different casing sensitivity

* chore: add xml docs to indicate defaults of ByLabelTextOptions

* fix: make classes add public

* fix: remove project references

* fix: move to source generator to public

* chore: switch to use wrapper component for tests

* chore: switch to use wrapper component for tests

* chore: rename to labelquerycounter for re-rendering test

* fix: remove warnings

* refactor: remove string duplication in tests

* fix: remove nullability warning

* fix: add sealed to remove warnings

* feat: add support for whitespace

* add xml comments

* fix: labelElement can be null if not found

* chore: fix indention

* chore: remove duplicated word

* fix: make label options immutable

* test: verify generate test output

* chore: remove whitespace in test case name

* refactor: simplify null check

* fix: cover scenario where wrapped label has nested HTML

* fix: rename test

* test: add additional test for nested html with for attributes

* docs: cover FindByLabelText and update verify markup section to discuss different markup verify approaches

* docs: verify-markup.md

Co-authored-by: Steven Giesel <[email protected]>

* refactor: use configure options pattern instead of passing option object

---------

Co-authored-by: Egil Hansen <[email protected]>
Co-authored-by: Steven Giesel <[email protected]>
  • Loading branch information
3 people authored Mar 17, 2024
1 parent 3ad9984 commit c40735b
Show file tree
Hide file tree
Showing 23 changed files with 734 additions and 61 deletions.
111 changes: 58 additions & 53 deletions docs/site/docs/verification/verify-markup.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,63 @@ title: Verifying markup from a component

# Verifying markup from a component

When a component is rendered in a test, the result is a <xref:Bunit.IRenderedFragment> or a <xref:Bunit.IRenderedComponent`1>. Through these, it is possible to access the rendered markup (HTML) of the component and, in the case of <xref:Bunit.IRenderedComponent`1>, the instance of the component.
Generally, the strategy for verifying markup produced by components depends on whether you are creating reusable component library or a single-use Blazor app component.

> [!NOTE]
> An <xref:Bunit.IRenderedComponent`1> inherits from <xref:Bunit.IRenderedFragment>. This page will only cover features of the <xref:Bunit.IRenderedFragment> type. <xref:Bunit.IRenderedComponent`1> is covered on the <xref:verify-component-state> page.
With a **reusable component library**, the markup produced may be considered part of the externally observable behavior of the component, and that should thus be verified, since users of the component may depend on the markup having a specific structure. Consider using `MarkupMatches` and semantic comparison described below to get the best protection against regressions and good maintainability.

When **building components for a Blazor app**, the externally observable behavior of components are how they visibly look and behave from an end-users point of view, e.g. what the user sees and interact with in a browser. In this scenario, consider use `FindByLabelText` and related methods described below to inspect and assert against individual elements look and feel, for a good balance between protection against regressions and maintainability. Learn more about this testing approach at https://testing-library.com.

This page covers the following **verification approaches:**

- Basic verification of raw markup
- Semantic comparison of markup
- Inspecting the individual DOM nodes in the DOM tree
- Semantic comparison of markup
- Finding expected differences in markup between renders
- Verification of raw markup

The following sections will cover each of these.

## Basic verification of raw markup
## Result of rendering components

To access the rendered markup of a component, just use the <xref:Bunit.IRenderedFragment.Markup> property on <xref:Bunit.IRenderedFragment>. This holds the *raw* HTML from the component as a `string`.
When a component is rendered in a test, the result is a <xref:Bunit.IRenderedFragment> or a <xref:Bunit.IRenderedComponent`1>. Through these, it is possible to access the rendered markup (HTML) of the component and, in the case of <xref:Bunit.IRenderedComponent`1>, the instance of the component.

> [!WARNING]
> Be aware that all indentions and whitespace in your components (`.razor` files) are included in the raw rendered markup, so it is often wise to normalize the markup string a little. For example, via the string `Trim()` method to make the tests more stable. Otherwise, a change to the formatting in your components might break the tests unnecessarily when it does not need to.
>
> To avoid these issues and others related to asserting against raw markup, use the semantic HTML comparer that comes with bUnit, described in the next section.
> [!NOTE]
> An <xref:Bunit.IRenderedComponent`1> inherits from <xref:Bunit.IRenderedFragment>. This page will only cover features of the <xref:Bunit.IRenderedFragment> type. <xref:Bunit.IRenderedComponent`1> is covered on the <xref:verify-component-state> page.
To get the markup as a string, do the following:
## Inspecting DOM nodes

[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=16&end=19&highlight=3)]
The rendered markup from a component is available as a DOM node through the <xref:Bunit.IRenderedFragment.Nodes> property on <xref:Bunit.IRenderedFragment>. The nodes and element types comes from [AngleSharp](https://anglesharp.github.io/) that follows the W3C DOM API specifications and gives you the same results as a state-of-the-art browser’s implementation of the DOM API in JavaScript. Besides the official DOM API, AngleSharp and bUnit add some useful extension methods on top. This makes working with DOM nodes convenient.

### Finding DOM elements

bUnit supports multiple different ways of searching and querying the rendered HTML elements:

- `FindByLabelText(string labelText)` that takes a text string used to label an input element and returns an `IElement` as output, or throws an exception if none are found (this is included in the experimental library [bunit.web.query](https://www.nuget.org/packages/bunit.web.query)). Use this method when possible compared to the generic `Find` and `FindAll` methods.
- [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) takes a "CSS selector" as input and returns an `IElement` as output, or throws an exception if none are found.
- [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) takes a "CSS selector" as input and returns a list of `IElement` elements.

Let's see some examples of using the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) and [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) methods to query the `<FancyTable>` component listed below.

[!code-razor[FancyTable.razor](../../../samples/components/FancyTable.razor)]

To find the `<caption>` element and the first `<td>` elements in each row, do the following:

[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=54&end=57&highlight=3-4)]

Once you have one or more elements, you verify against them, such as by inspecting their properties through the DOM API. For example:

You can perform standard string assertions against the markup string, like checking whether it contains a value or is empty.
[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=59&end=61)]

#### Auto-refreshing Find() queries

An element found with the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) method will be updated if the component it came from is re-rendered.

However, that does not apply to elements that are found by traversing the DOM tree via the <xref:Bunit.IRenderedFragment.Nodes> property on <xref:Bunit.IRenderedFragment>, for example, as those nodes do not know when their root component is re-rendered. Consequently, they don’t know when they should be updated.

As a result of this, it is always recommended to use the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) method when searching for a single element. Alternatively, always reissue the query whenever you need the element.

#### Auto-refreshable FindAll() queries

The [`FindAll(string cssSelector, bool enableAutoRefresh = false)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) method has an optional parameter, `enableAutoRefresh`, which when set to `true` will return a collection of `IElement`. This automatically refreshes itself when the component the elements came from is re-rendered.

## Semantic comparison of markup

Expand Down Expand Up @@ -91,45 +120,6 @@ The semantic HTML comparer can be customized to make a test case even more stabl

Learn more about the customization options on the <xref:semantic-html-comparison> page.

## Inspecting DOM nodes

The rendered markup from a component is available as a DOM node through the <xref:Bunit.IRenderedFragment.Nodes> property on <xref:Bunit.IRenderedFragment>, as well as the `Find(string cssSelector)` and `FindAll(string cssSelector)` extension methods on <xref:Bunit.IRenderedFragment>.

The <xref:Bunit.IRenderedFragment.Nodes> property and the `FindAll()` method return an [AngleSharp](https://anglesharp.github.io/) `INodeList` type, and the `Find()` method returns an [AngleSharp](https://anglesharp.github.io/) `IElement` type.

The DOM API in AngleSharp follows the W3C DOM API specifications and gives you the same results as a state-of-the-art browser’s implementation of the DOM API in JavaScript. Besides the official DOM API, AngleSharp and bUnit add some useful extension methods on top. This makes working with DOM nodes convenient.

### Finding nodes with the Find() and FindAll() methods

Users of the famous JavaScript framework [jQuery](https://jquery.com/) will recognize these two methods:

- [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) takes a "CSS selector" as input and returns an `IElement` as output, or throws an exception if none are found.
- [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) takes a "CSS selector" as input and returns a list of `IElement` elements.

Let's see some examples of using the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) and [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) methods to query the `<FancyTable>` component listed below.

[!code-razor[FancyTable.razor](../../../samples/components/FancyTable.razor)]

To find the `<caption>` element and the first `<td>` elements in each row, do the following:

[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=54&end=57&highlight=3-4)]

Once you have one or more elements, you verify against them, such as by inspecting their properties through the DOM API. For example:

[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=59&end=61)]

#### Auto-refreshing Find() queries

An element found with the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) method will be updated if the component it came from is re-rendered.

However, that does not apply to elements that are found by traversing the DOM tree via the <xref:Bunit.IRenderedFragment.Nodes> property on <xref:Bunit.IRenderedFragment>, for example, as those nodes do not know when their root component is re-rendered. Consequently, they don’t know when they should be updated.

As a result of this, it is always recommended to use the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) method when searching for a single element. Alternatively, always reissue the query whenever you need the element.

#### Auto-refreshable FindAll() queries

The [`FindAll(string cssSelector, bool enableAutoRefresh = false)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) method has an optional parameter, `enableAutoRefresh`, which when set to `true` will return a collection of `IElement`. This automatically refreshes itself when the component the elements came from is re-rendered.

## Finding expected differences

It can sometimes be easier to verify that an expected change, and only that change, has occurred in the rendered markup than it can be to specify how all the rendered markup should look after re-rendering.
Expand Down Expand Up @@ -178,3 +168,18 @@ This is what happens in the test:
8. Finally the last item in the list is found and clicked, and the <xref:Bunit.IRenderedFragment.GetChangesSinceSnapshot> method is used to find the changes, a single diff, which is verified as a removal of the second item.

As mentioned earlier, the `IDiff` assertion helpers are still experimental. Any feedback and suggestions for improvements should be directed to the [related issue](https://github.com/egil/bUnit/issues/84) on GitHub.

## Verification of raw markup

To access the rendered markup of a component, just use the <xref:Bunit.IRenderedFragment.Markup> property on <xref:Bunit.IRenderedFragment>. This holds the *raw* HTML from the component as a `string`.

> [!WARNING]
> Be aware that all indentions and whitespace in your components (`.razor` files) are included in the raw rendered markup, so it is often wise to normalize the markup string a little. For example, via the string `Trim()` method to make the tests more stable. Otherwise, a change to the formatting in your components might break the tests unnecessarily when it does not need to.
>
> To avoid these issues and others related to asserting against raw markup, use the semantic HTML comparer that comes with bUnit, described in the next section.
To get the markup as a string, do the following:

[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=16&end=19&highlight=3)]

Standard string assertions can be performed against the markup string, such as checking whether it contains a value or is empty.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Bunit.Web.AngleSharp;
/// Represents a wrapper around an <typeparamref name="TElement"/>.
/// </summary>
[GeneratedCodeAttribute("Bunit.Web.AngleSharp", "1.0.0.0")]
internal interface IElementWrapper<out TElement> where TElement : class, IElement
public interface IElementWrapper<out TElement> where TElement : class, IElement
{
/// <summary>
/// Gets the wrapped element.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace Bunit.Web.AngleSharp;
/// Represents an <see cref="IElement"/> factory, used by a <see cref="WrapperBase{TElement}"/>.
/// </summary>
[GeneratedCodeAttribute("Bunit.Web.AngleSharp", "1.0.0.0")]
internal interface IElementWrapperFactory
public interface IElementWrapperFactory
{
/// <summary>
/// A method that returns the latest version of the element to wrap.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Bunit.Web.AngleSharp;
/// </summary>
[DebuggerNonUserCode]
[GeneratedCodeAttribute("Bunit.Web.AngleSharp", "1.0.0.0")]
internal abstract class WrapperBase<TElement> : IElementWrapper<TElement>
public abstract class WrapperBase<TElement> : IElementWrapper<TElement>
where TElement : class, IElement
{
private readonly IElementWrapperFactory elementFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,16 @@ private static void GenerateWrapperFactory(StringBuilder source, IEnumerable<INa
{
source.AppendLine("""namespace Bunit.Web.AngleSharp;""");
source.AppendLine();
source.AppendLine("/// <summary>");
source.AppendLine("/// Provide helpers for wrapped HTML elements.");
source.AppendLine("/// </summary>");
source.AppendLine("[System.CodeDom.Compiler.GeneratedCodeAttribute(\"Bunit.Web.AngleSharp\", \"1.0.0.0\")]");
source.AppendLine($"internal static class WrapperExtensions");
source.AppendLine("public static class WrapperExtensions");
source.AppendLine("{");
source.AppendLine();
source.AppendLine("/// <summary>");
source.AppendLine("/// Provide wrapper to be used when elements re-render.");
source.AppendLine("/// </summary>");
source.AppendLine($"\tpublic static global::AngleSharp.Dom.IElement WrapUsing<TElementFactory>(this global::AngleSharp.Dom.IElement element, TElementFactory elementFactory) where TElementFactory : Bunit.Web.AngleSharp.IElementWrapperFactory => element switch");
source.AppendLine("\t{");

Expand Down
31 changes: 31 additions & 0 deletions src/bunit.web.query/ByLabelTextElementFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using AngleSharp.Dom;
using Bunit.Web.AngleSharp;

namespace Bunit;

internal sealed class ByLabelTextElementFactory : IElementWrapperFactory
{
private readonly IRenderedFragment testTarget;
private readonly string labelText;
private readonly ByLabelTextOptions options;

public Action? OnElementReplaced { get; set; }

public ByLabelTextElementFactory(IRenderedFragment testTarget, string labelText, ByLabelTextOptions options)
{
this.testTarget = testTarget;
this.labelText = labelText;
this.options = options;
testTarget.OnMarkupUpdated += FragmentsMarkupUpdated;
}

private void FragmentsMarkupUpdated(object? sender, EventArgs args)
=> OnElementReplaced?.Invoke();

public TElement GetElement<TElement>() where TElement : class, IElement
{
var element = testTarget.FindByLabelTextInternal(labelText, options) as TElement;

return element ?? throw new ElementRemovedFromDomException(labelText);
}
}
17 changes: 17 additions & 0 deletions src/bunit.web.query/Labels/ByLabelTextOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Bunit;

/// <summary>
/// Allows overrides of behavior for FindByLabelText method
/// </summary>
public record class ByLabelTextOptions
{
/// <summary>
/// The default behavior used by FindByLabelText if no overrides are specified
/// </summary>
internal static readonly ByLabelTextOptions Default = new();

/// <summary>
/// The StringComparison used for comparing the desired Label Text to the resulting HTML. Defaults to Ordinal (case sensitive).
/// </summary>
public StringComparison ComparisonType { get; set; } = StringComparison.Ordinal;
}
18 changes: 18 additions & 0 deletions src/bunit.web.query/Labels/LabelElementExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using AngleSharp.Dom;

namespace Bunit;

internal static class LabelElementExtensions
{
internal static bool IsHtmlElementThatCanHaveALabel(this IElement element) => element.NodeName switch
{
"INPUT" => true,
"SELECT" => true,
"TEXTAREA" => true,
"BUTTON" => true,
"METER" => true,
"OUTPUT" => true,
"PROGRESS" => true,
_ => false
};
}
31 changes: 31 additions & 0 deletions src/bunit.web.query/Labels/LabelNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace Bunit;

/// <summary>
/// Represents a failure to find an element in the searched target
/// using the Label's text.
/// </summary>
[Serializable]
public class LabelNotFoundException : Exception
{
/// <summary>
/// Gets the Label Text used to search with.
/// </summary>
public string LabelText { get; } = "";

/// <summary>
/// Initializes a new instance of the <see cref="LabelNotFoundException"/> class.
/// </summary>
/// <param name="labelText"></param>
public LabelNotFoundException(string labelText)
: base($"Unable to find a label with the text of '{labelText}'.")
{
LabelText = labelText;
}


/// <summary>
/// Initializes a new instance of the <see cref="LabelNotFoundException"/> class.
/// </summary>
protected LabelNotFoundException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
50 changes: 50 additions & 0 deletions src/bunit.web.query/Labels/LabelQueryExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using AngleSharp.Dom;
using Bunit.Labels.Strategies;

namespace Bunit;

/// <summary>
/// Extension methods for querying IRenderedFragments by Label
/// </summary>
public static class LabelQueryExtensions
{
private static readonly IReadOnlyList<ILabelTextQueryStrategy> LabelTextQueryStrategies =
[
// This is intentionally in the order of most likely to minimize strategies tried to find the label
new LabelTextUsingForAttributeStrategy(),
new LabelTextUsingAriaLabelStrategy(),
new LabelTextUsingWrappedElementStrategy(),
new LabelTextUsingAriaLabelledByStrategy(),
];

/// <summary>
/// Returns the first element (i.e. an input, select, textarea, etc. element) associated with the given label text.
/// </summary>
/// <param name="renderedFragment">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 FindByLabelText.</param>
public static IElement FindByLabelText(this IRenderedFragment renderedFragment, string labelText, Action<ByLabelTextOptions>? configureOptions = null)
{
var options = ByLabelTextOptions.Default;
if (configureOptions is not null)
{
options = options with { };
configureOptions.Invoke(options);
}

return FindByLabelTextInternal(renderedFragment, labelText, options) ?? throw new LabelNotFoundException(labelText);
}

internal static IElement? FindByLabelTextInternal(this IRenderedFragment renderedFragment, string labelText, ByLabelTextOptions options)
{
foreach (var strategy in LabelTextQueryStrategies)
{
var element = strategy.FindElement(renderedFragment, labelText, options);

if (element is not null)
return element;
}

return null;
}
}
Loading

0 comments on commit c40735b

Please sign in to comment.