diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a52b66ad..cd53d67a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,7 @@ on: push: branches: - main + - v3 paths: - 'src/**' - 'tests/**' @@ -44,8 +45,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x @@ -126,8 +125,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x @@ -225,8 +222,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x @@ -256,7 +251,7 @@ jobs: - name: 🧪 Run sample unit tests working-directory: docs/samples - run: dotnet test samples.sln -p:VSTestUseMSBuildOutput=false -f net8.0 + run: dotnet test samples.sln -p:VSTestUseMSBuildOutput=false -f net10.0 - name: 📄 Build docs working-directory: ./docs/site diff --git a/.github/workflows/docs-deploy.yml b/.github/workflows/docs-deploy.yml index 35f3bbdfe..7b9be3aa8 100644 --- a/.github/workflows/docs-deploy.yml +++ b/.github/workflows/docs-deploy.yml @@ -73,8 +73,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c6284e036..72d934d0a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -63,8 +63,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x diff --git a/CHANGELOG.md b/CHANGELOG.md index e5b9f7677..3a21227b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,21 @@ All notable changes to **bUnit** will be documented in this file. The project ad ## [Unreleased] +### Added + +- `INode.GetOwningComponent()` and its generic overload, which return the rendered component that rendered a DOM node. Reported by [@egil](https://github.com/egil) in #153. +- `Parent()`, `Root()`, `GetAncestors()`, `GetChildren()` and its generic overload on `IRenderedComponent`, for navigating the component tree. Reported by [@egil](https://github.com/egil) in #1180. + +### Changed + +- **Breaking:** all rendered components in a render tree now share a single DOM. Previously each rendered component parsed its own markup into its own document, so an element found through a child component had no ancestors outside that child. Consequences: + - Events raised on an element found through a child component now bubble into the markup rendered by its ancestor components, as they do in a browser. Reported by [@JelleHissink](https://github.com/JelleHissink) in #983. + - `Find` and `FindAll` on a child component evaluate positional and combinator selectors (`:first-child`, `+`, `~`, ...) against the whole tree rather than the component's markup in isolation. + - An `option` element rendered by a child component, inside a `select` element rendered by an ancestor with a matching `value` attribute, now renders as `selected`, matching what the ancestor's markup shows. + + A component whose markup starts or ends with text, or that the HTML parser relocates, still falls back to its own document, since its nodes cannot be identified in the shared one. +- Events raised on an element obtained through `FindComponent` no longer stop at the child component's own markup, so a submit button in a child component triggers the `@onsubmit` handler on the `form` element rendered by its parent. Reported by [@JelleHissink](https://github.com/JelleHissink) in #983. + ### Fixed - `DisposeComponentsAsync()` could dispose nothing when the renderer's dispatcher was busy, e.g. with a timer calling `InvokeAsync`. Reported by [@xfunc-tim-schneider](https://github.com/xfunc-tim-schneider) in #1939. Fixed by [@linkdotnet](https://github.com/linkdotnet). diff --git a/Directory.Packages.props b/Directory.Packages.props index 8a23376ef..3d275125a 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -26,36 +26,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/README.md b/README.md index 4208f1d12..fda024d9f 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,8 @@ To get started, head to the [getting started documentation](https://bunit.dev/do | bUnit version | .NET version | | ------------- | ------------------------------- | | 1.x | ≥ .netcore3.1 && ≤ .net 9 | -| 2.x | ≥ .net8 | +| 2.x | ≥ .net8 && ≤ .net 11 | +| 3.x | ≥ .net10 | For a migration guide, see [Upgrading bUnit](https://bunit.dev/docs/migrations/index.html). diff --git a/docs/samples/components/bunit.docs.samples.csproj b/docs/samples/components/bunit.docs.samples.csproj index 88949209f..9e1e852d7 100644 --- a/docs/samples/components/bunit.docs.samples.csproj +++ b/docs/samples/components/bunit.docs.samples.csproj @@ -1,7 +1,7 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit.Docs.Samples enable CA1014,NU5104 diff --git a/docs/samples/tests/Directory.Build.props b/docs/samples/tests/Directory.Build.props index 8071ce9d1..9a5722898 100644 --- a/docs/samples/tests/Directory.Build.props +++ b/docs/samples/tests/Directory.Build.props @@ -1,6 +1,6 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 false true false diff --git a/docs/site/docs/extensions/bunit-generators.md b/docs/site/docs/extensions/bunit-generators.md index c9c072908..74d9b3f97 100644 --- a/docs/site/docs/extensions/bunit-generators.md +++ b/docs/site/docs/extensions/bunit-generators.md @@ -53,12 +53,12 @@ To use the generator, the **Interceptor** feature has to be used inside the cspr ```xml - net8.0 + net10.0 $(InterceptorsPreviewNamespaces);Bunit ``` -Due to the usage of **Interceptors** the generator is only available for .NET 8.0 and above. The generator does create a `partial` class, so it can be extended with custom logic if needed. +Due to the usage of **Interceptors** the generator requires .NET 10.0 and above, matching bUnit's minimum supported target framework. The generator does create a `partial` class, so it can be extended with custom logic if needed. ## Component stub generator via `ComponentStubAttribute` diff --git a/docs/site/docs/getting-started/create-test-project.md b/docs/site/docs/getting-started/create-test-project.md index a3b526ada..f1b9c558a 100644 --- a/docs/site/docs/getting-started/create-test-project.md +++ b/docs/site/docs/getting-started/create-test-project.md @@ -148,10 +148,10 @@ dotnet add package bunit --version #{NBGV_NuGetPackageVersion}# The test projects setting needs to be set to the following: - the project's SDK needs to be set to `Microsoft.NET.Sdk.Razor` (this does not work with **TUnit** - a more detailed explanation can be found below) -- set the `` to `net8.0` +- set the `` to `net10.0` > [!NOTE] -> bUnit works with `net8.0` and above as well. +> bUnit works with `net10.0` and above as well. To do so, change the first part of the test projects `.csproj` file to look like this.: @@ -159,7 +159,7 @@ To do so, change the first part of the test projects `.csproj` file to look like - net8.0 + net10.0 ... @@ -182,7 +182,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false @@ -211,7 +211,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false Exe @@ -241,7 +241,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false @@ -267,7 +267,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false @@ -293,7 +293,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false false diff --git a/docs/site/docs/interaction/render-modes.md b/docs/site/docs/interaction/render-modes.md index d019abba6..45ca1d70f 100644 --- a/docs/site/docs/interaction/render-modes.md +++ b/docs/site/docs/interaction/render-modes.md @@ -75,7 +75,7 @@ public void StaticRendering() # [Razor test code](#tab/razor) ```razor -@inherits TestContext +@inherits BunitContext @code { [Fact] public void InteractiveServer() @@ -108,7 +108,7 @@ public void StaticRendering() *** ## Setting the `RendererInfo` during testing -To control the `ComponentBase.RendererInfo` property during testing, use the method on the `TestContext` class. The `SetRendererInfo` method takes an nullable `RendererInfo` object as a parameter. Passing `null` will set the `ComponentBase.RendererInfo` to `null`. +To control the `ComponentBase.RendererInfo` property during testing, use the method on the `BunitContext` class. The `SetRendererInfo` method takes an nullable `RendererInfo` object as a parameter. Passing `null` will set the `ComponentBase.RendererInfo` to `null`. A component (`AssistentComponent.razor`) might check if interactivity is given to enable a button: @@ -154,4 +154,4 @@ public void SimulatingInteractiveServerRendering() ``` > [!NOTE] -> If a component under test uses the `ComponentBase.RendererInfo` property and the `SetRendererInfo` on `TestContext` hasn't been passed in a `RendererInfo` object, the renderer will throw an exception. \ No newline at end of file +> If a component under test uses the `ComponentBase.RendererInfo` property and the `SetRendererInfo` on `BunitContext` hasn't been passed in a `RendererInfo` object, the renderer will throw an exception. \ No newline at end of file diff --git a/docs/site/docs/interaction/trigger-event-handlers.md b/docs/site/docs/interaction/trigger-event-handlers.md index d8eb3ff8c..cd9497303 100644 --- a/docs/site/docs/interaction/trigger-event-handlers.md +++ b/docs/site/docs/interaction/trigger-event-handlers.md @@ -105,4 +105,26 @@ Example: ```csharp await cut.Find("button").ClickAsync(); -``` \ No newline at end of file +``` +## Events bubble across component boundaries + +Every component in a render tree shares one DOM, so an element found through a child +component still has its ancestors from the parent components around it. Events therefore +bubble the same way whether the element was found from the component under test or from +one of its children: + +```csharp +var cut = Render(); + +// Both of these trigger the @onsubmit handler on the
+// rendered by . +cut.Find("button").Click(); +cut.FindComponent().Find("button").Click(); +``` + +Use `GetOwningComponent()` on any element to get the component that rendered it, which is +covered in : + +```csharp +IRenderedComponent inner = cut.Find("button").GetOwningComponent(); +``` diff --git a/docs/site/docs/migrations/2to3.md b/docs/site/docs/migrations/2to3.md new file mode 100644 index 000000000..0ee106ebe --- /dev/null +++ b/docs/site/docs/migrations/2to3.md @@ -0,0 +1,51 @@ +--- +uid: migrating-from-2-to-3 +title: Migrating from 2.x to 3.x +--- + +# Migrating from bUnit 2.x to 3.x +This document describes the changes made in bUnit 3.x that may affect existing tests written for bUnit 2.x. + +## Dropped support for .NET 8 and .NET 9 + +bUnit 3.x drops support for `net8.0` and `net9.0`. The minimum supported target framework is now `net10.0`, and `net11.0` is also supported. + +To migrate, update your test project's `` (or ``) to `net10.0` or later: + +```diff +- net8.0 ++ net10.0 +``` + +## Removed obsolete and deprecated APIs + +bUnit 3.x removes APIs that were kept around for backwards compatibility with bUnit 1.x and were marked `[Obsolete]` or scheduled for removal: + +- `TestContext` class: use `BunitContext` instead. +- `RenderComponent()` and `RenderComponent(Action>?)`: use `Render()` instead. +- `BunitSignOutSessionStateManager`: this was a test double for the obsolete `SignOutSessionStateManager` from `Microsoft.AspNetCore.Components.WebAssembly.Authentication` and has been removed. `AddAuthorization()` no longer registers it in the service collection. + +## `BunitContext.DefaultWaitTimeout` is no longer static + +`BunitContext.DefaultWaitTimeout` used to be a `static` property, so setting it in one test affected the timeout used by every other test running in the same process, including tests running concurrently. It is now an instance property, so each `BunitContext` (and each test class deriving from it) has its own timeout, used by both `WaitForXXX` helpers and its own `JSInterop`. + +To migrate, set the timeout on the test's `BunitContext` instance instead of the static property. If every test in a class needs a longer timeout, the constructor is a good place to set it once: + +```diff + public class MyComponentTest : BunitContext + { ++ public MyComponentTest() ++ { ++ DefaultWaitTimeout = TimeSpan.FromSeconds(10); ++ } + + [Fact] + public void MyTest() + { +- BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(10); + // ... + } + } +``` + +Setting it on a specific `BunitContext` instance (rather than a class deriving from it) works the same way: `context.DefaultWaitTimeout = TimeSpan.FromSeconds(10);`. \ No newline at end of file diff --git a/docs/site/docs/migrations/index.md b/docs/site/docs/migrations/index.md index 35f8abeae..4969e3e43 100644 --- a/docs/site/docs/migrations/index.md +++ b/docs/site/docs/migrations/index.md @@ -7,4 +7,5 @@ title: Migrations This section covers the migration across major versions of bUnit. The mirations themselves also list the link to the old version of the documentation (including the old API documentation). + - - \ No newline at end of file diff --git a/docs/site/docs/providing-input/seeding-assets.md b/docs/site/docs/providing-input/seeding-assets.md index af523698a..d821c04a8 100644 --- a/docs/site/docs/providing-input/seeding-assets.md +++ b/docs/site/docs/providing-input/seeding-assets.md @@ -5,7 +5,7 @@ title: Seeding static assets (Assets) # Seeding static assets (`Assets`) -This article explains how to seed the `Assets` property of components under test in bUnit. This is supported for .NET 9 and later. +This article explains how to seed the `Assets` property of components under test in bUnit. Since .NET 9, components can access static assets mapped by [`MapStaticAssets`](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/map-static-files?view=aspnetcore-9.0) through the [`ComponentBase.Assets`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.componentbase.assets?view=aspnetcore-9.0) property, e.g. to resolve fingerprinted URLs: diff --git a/docs/site/docs/toc.md b/docs/site/docs/toc.md index 53fe7e811..f681edec4 100644 --- a/docs/site/docs/toc.md +++ b/docs/site/docs/toc.md @@ -20,6 +20,7 @@ # [Verifying output](xref:verification) ## [Verify markup](xref:verify-markup) ## [Verify component state](xref:verify-component-state) +## [Find the component that rendered an element](xref:find-owning-component) ## [Customizing semantic comparison](xref:semantic-html-comparison) ## [Assertion of asynchronous changes](xref:async-assertion) @@ -37,6 +38,7 @@ ## [bunit.generators](xref:bunit-generators) # [Migrations](xref:migrations) +## [2.x to 3.x](xref:migrating-from-2-to-3) ## [1.x to 2.x](xref:migrating-from-1-to-2) # [Miscellaneous testing tips](xref:misc-test-tips) diff --git a/docs/site/docs/verification/find-owning-component.md b/docs/site/docs/verification/find-owning-component.md new file mode 100644 index 000000000..0e33a483d --- /dev/null +++ b/docs/site/docs/verification/find-owning-component.md @@ -0,0 +1,78 @@ +--- +uid: find-owning-component +title: Finding the component that rendered an element +--- + +# Finding the component that rendered an element + +The DOM query API is often the quickest way to reach an interesting part of the rendered +output. +takes you from a node found that way back to the component that rendered it, so you can +assert on that component's state: + +```csharp +var cut = Render(); + +IRenderedComponent owner = cut.Find("li.done").GetOwningComponent(); + +owner.Instance.ShouldBeOfType(); +``` + +Use the generic overload, +, +when you know which component type you are after. It returns a strongly typed +, so the component instance and all the usual verification +methods are available: + +```csharp +var cut = Render(); + +IRenderedComponent item = cut.Find("li.done").GetOwningComponent(); + +item.Instance.IsDone.ShouldBeTrue(); +item.MarkupMatches("
  • Buy milk
  • "); +``` + +## Which component is returned + +The **innermost** component that rendered the node. Given a `` that renders a +`
      ` and a `` per entry, `cut.Find("ul").GetOwningComponent()` returns the +`` and `cut.Find("li").GetOwningComponent()` returns the ``. + +A few details worth knowing: + +- **Nodes that are not elements resolve through their closest element.** Calling it on a text + node returns the component that rendered the element containing that text. +- **Content passed as a `RenderFragment` belongs to the receiving component.** A + `ChildContent` written in the parent is rendered into the child's render tree, so + `GetOwningComponent()` names the child. This matches what the child's + already showed. +- **bUnit's own root component is never returned.** Wrapper components with no markup of their + own, such as `CascadingValue`, lose to the component inside them. + +The generic overload widens the search outwards: if the innermost component is not a +`TComponent`, it walks up the component tree until it finds one, and throws + if there is none. That makes it a concise +way to reach a specific ancestor: + +```csharp +// The + +@code { + [Parameter] public string ButtonType { get; set; } = "button"; + + public int ClickCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/CounterChild.razor b/tests/bunit.testassets/SampleComponents/CounterChild.razor new file mode 100644 index 000000000..9ceb74bc7 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/CounterChild.razor @@ -0,0 +1,5 @@ + + +@code { + public int Count { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/EmptyChild.razor b/tests/bunit.testassets/SampleComponents/EmptyChild.razor new file mode 100644 index 000000000..bcf78df4a --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/EmptyChild.razor @@ -0,0 +1 @@ +@code { } diff --git a/tests/bunit.testassets/SampleComponents/GrandParentDivWithChildButton.razor b/tests/bunit.testassets/SampleComponents/GrandParentDivWithChildButton.razor new file mode 100644 index 000000000..14ffb0b01 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/GrandParentDivWithChildButton.razor @@ -0,0 +1,9 @@ +
      + +
      + +@code { + [Parameter] public bool StopPropagation { get; set; } + + public int ClickCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/LeadingTextChild.razor b/tests/bunit.testassets/SampleComponents/LeadingTextChild.razor new file mode 100644 index 000000000..f13c43287 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/LeadingTextChild.razor @@ -0,0 +1 @@ +Hello world diff --git a/tests/bunit.testassets/SampleComponents/ParentDivWithChildButton.razor b/tests/bunit.testassets/SampleComponents/ParentDivWithChildButton.razor new file mode 100644 index 000000000..f825322e5 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentDivWithChildButton.razor @@ -0,0 +1,9 @@ +
      + +
      + +@code { + [Parameter] public bool StopPropagation { get; set; } + + public int ClickCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/ParentFormWithChildButton.razor b/tests/bunit.testassets/SampleComponents/ParentFormWithChildButton.razor new file mode 100644 index 000000000..32cd65176 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentFormWithChildButton.razor @@ -0,0 +1,7 @@ + + + + +@code { + public int SubmitCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/ParentWithEmptyChild.razor b/tests/bunit.testassets/SampleComponents/ParentWithEmptyChild.razor new file mode 100644 index 000000000..14d74d9a5 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentWithEmptyChild.razor @@ -0,0 +1 @@ +
      diff --git a/tests/bunit.testassets/SampleComponents/ParentWithLeadingTextChild.razor b/tests/bunit.testassets/SampleComponents/ParentWithLeadingTextChild.razor new file mode 100644 index 000000000..33630436a --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentWithLeadingTextChild.razor @@ -0,0 +1 @@ +
      diff --git a/tests/bunit.testassets/SampleComponents/ParentWithTextOnlyChild.razor b/tests/bunit.testassets/SampleComponents/ParentWithTextOnlyChild.razor new file mode 100644 index 000000000..a34baa18a --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentWithTextOnlyChild.razor @@ -0,0 +1 @@ +

      Hello world

      diff --git a/tests/bunit.testassets/SampleComponents/SelectWithChildOptions.razor b/tests/bunit.testassets/SampleComponents/SelectWithChildOptions.razor new file mode 100644 index 000000000..ce2089b65 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/SelectWithChildOptions.razor @@ -0,0 +1,4 @@ + diff --git a/tests/bunit.testassets/SampleComponents/SiblingChildren.razor b/tests/bunit.testassets/SampleComponents/SiblingChildren.razor new file mode 100644 index 000000000..4f2cace32 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/SiblingChildren.razor @@ -0,0 +1,4 @@ +
      + + +
      diff --git a/tests/bunit.testassets/SampleComponents/TableWithChildRows.razor b/tests/bunit.testassets/SampleComponents/TableWithChildRows.razor new file mode 100644 index 000000000..78193fd34 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/TableWithChildRows.razor @@ -0,0 +1,6 @@ + + + + + +
      diff --git a/tests/bunit.testassets/SampleComponents/TextOnlyChild.razor b/tests/bunit.testassets/SampleComponents/TextOnlyChild.razor new file mode 100644 index 000000000..c3e9594dc --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/TextOnlyChild.razor @@ -0,0 +1,5 @@ +@ChildText + +@code { + [Parameter] public string ChildText { get; set; } = "child-text"; +} diff --git a/tests/bunit.testassets/bunit.testassets.csproj b/tests/bunit.testassets/bunit.testassets.csproj index b8d28daec..d26f5977a 100644 --- a/tests/bunit.testassets/bunit.testassets.csproj +++ b/tests/bunit.testassets/bunit.testassets.csproj @@ -1,7 +1,7 @@  - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit.TestAssets Bunit.TestAssets Library diff --git a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs b/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs index 9c3fb672b..132feff6a 100644 --- a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs +++ b/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs @@ -20,7 +20,7 @@ public class ComponentRenderingTest : BunitContext { public ComponentRenderingTest(ITestOutputHelper outputHelper) { - BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(10); + DefaultWaitTimeout = TimeSpan.FromSeconds(10); Services.AddXunitLogger(outputHelper); JSInterop.Mode = JSRuntimeMode.Loose; } diff --git a/tests/bunit.tests/EventDispatchExtensions/ChildComponentEventBubblingTest.cs b/tests/bunit.tests/EventDispatchExtensions/ChildComponentEventBubblingTest.cs new file mode 100644 index 000000000..e81e42be7 --- /dev/null +++ b/tests/bunit.tests/EventDispatchExtensions/ChildComponentEventBubblingTest.cs @@ -0,0 +1,67 @@ +namespace Bunit; + +/// +/// Verifies that events raised on an element found through a child components +/// bubble through the DOM rendered +/// by the child's ancestor components. See issue #983. +/// +public class ChildComponentEventBubblingTest : BunitContext +{ + [Fact(DisplayName = "Clicking a child component's element bubbles to the parent component's element")] + public void Test001() + { + var cut = Render(); + + cut.FindComponent().Find("button").Click(); + + cut.Instance.ClickCount.ShouldBe(1); + } + + [Fact(DisplayName = "Clicking a child component's submit button triggers the parent component's form")] + public void Test002() + { + var cut = Render(); + + cut.FindComponent().Find("button").Click(); + + cut.Instance.SubmitCount.ShouldBe(1); + } + + [Fact(DisplayName = "Bubbling from a child component's element is identical to bubbling from the parent's view of it")] + public void Test003() + { + var cut = Render(); + var child = cut.FindComponent(); + + cut.Find("button").Click(); + var (parentAfterFirst, childAfterFirst) = (cut.Instance.ClickCount, child.Instance.ClickCount); + + child.Find("button").Click(); + + cut.Instance.ClickCount.ShouldBe(parentAfterFirst + 1); + child.Instance.ClickCount.ShouldBe(childAfterFirst + 1); + } + + [Fact(DisplayName = "stopPropagation on a parent component's element stops bubbling from a child component's element")] + public void Test004() + { + var cut = Render(ps => ps.Add(p => p.StopPropagation, true)); + + cut.FindComponent().Find("button").Click(); + + cut.FindComponent().Instance.ClickCount.ShouldBe(1); + cut.Instance.ClickCount.ShouldBe(0); + } + + [Fact(DisplayName = "Events bubble through three levels of components")] + public void Test005() + { + var cut = Render(); + + cut.FindComponent().Find("button").Click(); + + cut.FindComponent().Instance.ClickCount.ShouldBe(1); + cut.FindComponent().Instance.ClickCount.ShouldBe(1); + cut.Instance.ClickCount.ShouldBe(1); + } +} diff --git a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs index 7bf444d62..caf4083a0 100644 --- a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs @@ -14,7 +14,7 @@ public class GeneralEventDispatchExtensionsTest : EventDispatchExtensionsTest +/// Verifies that a DOM node can be traced back to the component that +/// rendered it. See issue #153. +/// +public class ElementOwningComponentTest : BunitContext +{ + [Fact(DisplayName = "GetOwningComponent returns the component that rendered the element")] + public void Test001() + { + var cut = Render(); + + var owner = cut.Find("button").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent returns the same rendered component as FindComponent")] + public void Test002() + { + var cut = Render(); + var child = cut.FindComponent(); + + var owner = cut.Find("button").GetOwningComponent(); + + owner.ShouldBeSameAs(child); + } + + [Fact(DisplayName = "GetOwningComponent returns the parent component for an element it rendered")] + public void Test003() + { + var cut = Render(); + + var owner = cut.Find("#parent-div").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent walks outwards to the nearest component of that type")] + public void Test004() + { + var cut = Render(); + + var owner = cut.Find("button").GetOwningComponent(); + + owner.ShouldBeSameAs(cut.FindComponent()); + } + + [Fact(DisplayName = "GetOwningComponent throws when no ancestor of that type rendered the element")] + public void Test005() + { + var cut = Render(); + + Should.Throw( + () => cut.Find("button").GetOwningComponent()); + } + + [Fact(DisplayName = "GetOwningComponent resolves a descendant node to the component that rendered its element")] + public void Test006() + { + var cut = Render(); + + var owner = cut.Find("#child-row td").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent never returns a bUnit infrastructure component")] + public void Test007() + { + var cut = Render(); + + var owner = cut.Find("h1").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent throws for a node that was not rendered by bUnit")] + public void Test008() + { + using var parser = new Bunit.Rendering.BunitHtmlParser(); + var nodes = parser.Parse("

      foo

      "); + + Should.Throw(() => nodes[0].GetOwningComponent()); + } + + [Fact(DisplayName = "GetOwningComponent resolves an element of a component that has its own document")] + public void Test010() + { + // Markup starting with text cannot be located in the shared document, so the + // component is parsed into one of its own - both routes must still resolve. + var cut = Render(); + var child = cut.FindComponent(); + + child.Nodes[0].Owner.ShouldNotBeSameAs(cut.Nodes[0].Owner); + + child.Find("b").GetOwningComponent().ShouldBeSameAs(child); + cut.Find("b").GetOwningComponent().ShouldBeSameAs(child); + } + + [Fact(DisplayName = "GetOwningComponent resolves elements from separate render trees to their own component")] + public void Test009() + { + var first = Render(); + var second = Render(); + + first.Find("button").GetOwningComponent() + .ShouldBeSameAs(first.FindComponent()); + second.Find("button").GetOwningComponent() + .ShouldBeSameAs(second.FindComponent()); + } +} diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensions.Test.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensions.Test.cs index f0c4316c3..3861d8fcb 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensions.Test.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensions.Test.cs @@ -8,7 +8,7 @@ public class RenderedComponentWaitForElementsHelperExtensions : BunitContext public RenderedComponentWaitForElementsHelperExtensions(ITestOutputHelper testOutput) { - BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(10); + DefaultWaitTimeout = TimeSpan.FromSeconds(10); Services.AddXunitLogger(testOutput); } diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensionsTest.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensionsTest.cs index 295fdf844..217d02422 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensionsTest.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedComponentWaitForElementsHelperExtensionsTest.cs @@ -9,7 +9,7 @@ public class RenderedComponentWaitForElementsHelperExtensionsTest : BunitContext public RenderedComponentWaitForElementsHelperExtensionsTest(ITestOutputHelper testOutput) { - BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(10); + DefaultWaitTimeout = TimeSpan.FromSeconds(10); Services.AddXunitLogger(testOutput); } diff --git a/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs b/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs index 64859c4eb..13738d6cd 100644 --- a/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs +++ b/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs @@ -504,190 +504,7 @@ public void Test046() exception.Invocation.Identifier.ShouldBe(identifier); exception.Invocation.Arguments.ShouldBe(args); } - -#if !NET9_0_OR_GREATER - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with one argument")] - public void Test047() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - var args = new[] { "bar" }; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar")); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBe(args); - } - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with two arguments")] - public void Test048() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - var args = new[] { "bar", "baz" }; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz")); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBe(args); - } - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with three arguments")] - public void Test049() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - var args = new[] { "bar", "baz", "bau" }; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz", "bau")); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBe(args); - } - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with zero arguments")] - public void Test050() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier)); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBeEmpty(); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed one arguments.")] - public void Test055() - { - var identifier = "fooFunc"; - var args = new[] { "bar" }; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc", args); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar"); - actual.ShouldBe(expectedResult); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed two arguments.")] - public void Test056() - { - var identifier = "fooFunc"; - var args = new[] { "bar", "baz" }; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc", args); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz"); - actual.ShouldBe(expectedResult); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed three arguments.")] - public void Test057() - { - var identifier = "fooFunc"; - var args = new[] { "bar", "baz", "bao" }; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc", args); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz", "bao"); - actual.ShouldBe(expectedResult); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed zero arguments.")] - public void Test058() - { - var identifier = "fooFunc"; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc"); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier); - actual.ShouldBe(expectedResult); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier), then the invocation should be visible from the Invocations list"), AutoData] - public void Test310(string identifier) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - Array.Empty(), - typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0), then the invocation should be visible from the Invocations list"), AutoData] - public void Test306(string identifier, string arg0) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1), then the invocation should be visible from the Invocations list"), AutoData] - public void Test307(string identifier, string arg0, string arg1) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0, arg1); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1, arg2), then the invocation should be visible from the Invocations list"), AutoData] - public void Test308(string identifier, string arg0, string arg1, string arg2) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled( - identifier, arg0, arg1, arg2); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1, arg2 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } -#endif -#if NET10_0_OR_GREATER [Fact(DisplayName = "InvokeConstructorAsync returns IJSObjectReference in loose mode without setup")] public async Task Test400() { @@ -774,5 +591,4 @@ public async Task Test406() sut.Invocations["JsClass"].ShouldHaveSingleItem() .InvocationMethodName.ShouldBe("InvokeConstructorAsync"); } -#endif } diff --git a/tests/bunit.tests/JSInterop/BunitJSInteropTimeoutTest.cs b/tests/bunit.tests/JSInterop/BunitJSInteropTimeoutTest.cs index eb5cc4a28..e268cc2ec 100644 --- a/tests/bunit.tests/JSInterop/BunitJSInteropTimeoutTest.cs +++ b/tests/bunit.tests/JSInterop/BunitJSInteropTimeoutTest.cs @@ -2,12 +2,6 @@ namespace Bunit.JSInterop; -[CollectionDefinition(nameof(DefaultWaitTimeoutTestGroup), DisableParallelization = true)] -public sealed class DefaultWaitTimeoutTestGroup -{ -} - -[Collection(nameof(DefaultWaitTimeoutTestGroup))] public class BunitJSInteropTimeoutTest { [Fact(DisplayName = "JSRuntime invocation times out when handler is not configured")] @@ -15,34 +9,28 @@ public async Task Test309() { const string identifier = "testFunction"; - await WithDefaultWaitTimeout(TimeSpan.FromMilliseconds(100), async () => - { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; - sut.Setup(identifier); + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = TimeSpan.FromMilliseconds(100) }; + sut.Setup(identifier); - var invocationTask = sut.JSRuntime.InvokeAsync(identifier); + var invocationTask = sut.JSRuntime.InvokeAsync(identifier); - var exception = await Should.ThrowAsync(invocationTask.AsTask()); - exception.Invocation.Identifier.ShouldBe(identifier); - }); + var exception = await Should.ThrowAsync(invocationTask.AsTask()); + exception.Invocation.Identifier.ShouldBe(identifier); } [Fact(DisplayName = "Each pending invocation times out with its own invocation")] public async Task Test310() { - await WithDefaultWaitTimeout(TimeSpan.FromMilliseconds(100), async () => - { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; - sut.Setup(_ => true); + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = TimeSpan.FromMilliseconds(100) }; + sut.Setup(_ => true); - var first = sut.JSRuntime.InvokeAsync("first").AsTask(); - var second = sut.JSRuntime.InvokeAsync("second").AsTask(); + var first = sut.JSRuntime.InvokeAsync("first").AsTask(); + var second = sut.JSRuntime.InvokeAsync("second").AsTask(); - (await Should.ThrowAsync(first)) - .Invocation.Identifier.ShouldBe("first"); - (await Should.ThrowAsync(second)) - .Invocation.Identifier.ShouldBe("second"); - }); + (await Should.ThrowAsync(first)) + .Invocation.Identifier.ShouldBe("first"); + (await Should.ThrowAsync(second)) + .Invocation.Identifier.ShouldBe("second"); } [Fact(DisplayName = "A timed out invocation does not affect later invocations")] @@ -50,18 +38,15 @@ public async Task Test311() { const string identifier = "testFunction"; - await WithDefaultWaitTimeout(TimeSpan.FromMilliseconds(100), async () => - { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; - var handler = sut.Setup(identifier); + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = TimeSpan.FromMilliseconds(100) }; + var handler = sut.Setup(identifier); - await Should.ThrowAsync( - sut.JSRuntime.InvokeAsync(identifier).AsTask()); + await Should.ThrowAsync( + sut.JSRuntime.InvokeAsync(identifier).AsTask()); - handler.SetResult(42); + handler.SetResult(42); - (await sut.JSRuntime.InvokeAsync(identifier)).ShouldBe(42); - }); + (await sut.JSRuntime.InvokeAsync(identifier)).ShouldBe(42); } [Fact(DisplayName = "Setting a result while the timeout elapses does not crash the test host")] @@ -70,21 +55,18 @@ public async Task Test312() const string identifier = "testFunction"; var timeout = TimeSpan.FromMilliseconds(2); - await WithDefaultWaitTimeout(timeout, async () => - { - var workers = Enumerable - .Range(0, Math.Max(4, Environment.ProcessorCount)) - .Select(_ => Task.Run(() => RaceResultAgainstTimeout(identifier, timeout, iterations: 250))); + var workers = Enumerable + .Range(0, Math.Max(4, Environment.ProcessorCount)) + .Select(_ => Task.Run(() => RaceResultAgainstTimeout(identifier, timeout, iterations: 250))); - await Task.WhenAll(workers); - }); + await Task.WhenAll(workers); } private static async Task RaceResultAgainstTimeout(string identifier, TimeSpan timeout, int iterations) { for (var i = 0; i < iterations; i++) { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = timeout }; var handler = sut.Setup(identifier); var invocationTask = sut.JSRuntime.InvokeAsync(identifier).AsTask(); @@ -105,18 +87,4 @@ private static async Task RaceResultAgainstTimeout(string identifier, TimeSpan t exception.InnerException.ShouldBeOfType(); } } - - private static async Task WithDefaultWaitTimeout(TimeSpan timeout, Func test) - { - var originalTimeout = BunitContext.DefaultWaitTimeout; - BunitContext.DefaultWaitTimeout = timeout; - try - { - await test(); - } - finally - { - BunitContext.DefaultWaitTimeout = originalTimeout; - } - } } diff --git a/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs b/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs index d99bd9dd3..6342f3569 100644 --- a/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs +++ b/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs @@ -246,18 +246,6 @@ public void Test070() jsRuntime.ShouldBeAssignableTo(); } -#if !NET9_0_OR_GREATER - [Fact(DisplayName = "IJSObjectReference can be cast to IJSUnmarshalledObjectReference")] - public void Test071() - { - JSInterop.Mode = JSRuntimeMode.Loose; - - var jsRuntime = GetBunitJSObjectReference(); - - jsRuntime.ShouldBeAssignableTo(); - } -#endif - [Fact(DisplayName = "IJSInProcessObjectReference-invocations is handled by handlers from BunitJSInterop")] public async Task Test080() { @@ -279,114 +267,6 @@ public async Task Test080() JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(["baz"]); } -#if !NET9_0_OR_GREATER - [Fact(DisplayName = "IJSUnmarshalledObjectReference-invocations is handled by handlers from BunitJSInterop")] - [Obsolete("Because we are calling obsolete methods in test.")] - public async Task Test081() - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalled = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - await jsUnmarshalled.InvokeAsync("bar1"); - await jsUnmarshalled.InvokeAsync("bar2", "baz"); - await jsUnmarshalled.InvokeVoidAsync("bar3"); - await jsUnmarshalled.InvokeVoidAsync("bar4", "baz"); - jsUnmarshalled.Invoke("bar5"); - jsUnmarshalled.Invoke("bar6", "baz"); - jsUnmarshalled.InvokeUnmarshalled("bar7"); - jsUnmarshalled.InvokeUnmarshalled("bar8", "baz"); - jsUnmarshalled.InvokeUnmarshalled("bar9", "baz", "boo"); - jsUnmarshalled.InvokeUnmarshalled("bar10", "baz", "boo", "bah"); - - JSInterop.VerifyInvoke("bar1"); - JSInterop.VerifyInvoke("bar2").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar3"); - JSInterop.VerifyInvoke("bar4").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar5"); - JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar7"); - JSInterop.VerifyInvoke("bar8").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar9").Arguments.ShouldBe(["baz", "boo"]); - JSInterop.VerifyInvoke("bar10").Arguments.ShouldBe(["baz", "boo", "bah"]); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test310(string identifier) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: Array.Empty(), - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test306(string identifier, string arg0) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test307(string identifier, string arg0, string arg1) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0, arg1); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1, arg2), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test308(string identifier, string arg0, string arg1, string arg2) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled( - identifier, arg0, arg1, arg2); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1, arg2 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } -#endif [Theory(DisplayName = "When calling InvokeVoidAsync, then the invocation should be visible from the Invocations list"), AutoData] public void Test302(string identifier, string[] args, CancellationToken cancellationToken) diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs index 42a7a5607..784ba7e62 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs @@ -15,9 +15,7 @@ public void Test001(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.Items, CreateItems(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ChildContent, item => $"

      {item}

      ")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -29,9 +27,7 @@ public void Test002(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.Items, CreateItems(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ItemContent, item => $"

      {item}

      ")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -43,9 +39,7 @@ public void Test010(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ChildContent, item => $"

      {item}

      ")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -57,9 +51,7 @@ public void Test011(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ItemContent, item => $"

      {item}

      ")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -119,9 +111,7 @@ public void Test030(int itemsInDataSource, float itemSize, int overscanCount) .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) .Add(p => p.ItemContent, item => $"

      {item}

      ") .Add(p => p.ItemSize, itemSize) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.OverscanCount, overscanCount)); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -134,9 +124,7 @@ public void Test040(int itemsInDataSource) var cut = Render>(ps => ps .Add(p => p.ItemsProvider, _ => ValueTask.FromResult(new ItemsProviderResult(Array.Empty(), itemsInDataSource))) .Add(p => p.ItemContent, item => @$"

      {item}

      ") -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.Placeholder, _ => @"

      ")); cut.FindAll(".placeholder").Count.ShouldBe(itemsInDataSource); diff --git a/tests/bunit.tests/Rendering/AssetsTest.razor b/tests/bunit.tests/Rendering/AssetsTest.razor index 3f2dd16aa..84c757c52 100644 --- a/tests/bunit.tests/Rendering/AssetsTest.razor +++ b/tests/bunit.tests/Rendering/AssetsTest.razor @@ -1,6 +1,3 @@ -@code{ - #if NET9_0_OR_GREATER -} @using Bunit.TestAssets.Assets; @inherits BunitContext @code { @@ -101,6 +98,3 @@ ex.ParamName.ShouldBe("properties"); } } -@code{ - #endif -} diff --git a/tests/bunit.tests/Rendering/ComponentTreeNavigationTest.cs b/tests/bunit.tests/Rendering/ComponentTreeNavigationTest.cs new file mode 100644 index 000000000..7cc940f18 --- /dev/null +++ b/tests/bunit.tests/Rendering/ComponentTreeNavigationTest.cs @@ -0,0 +1,81 @@ +namespace Bunit.Rendering; + +///

      +/// Verifies navigation of the component tree. See issue #1180. +/// +public class ComponentTreeNavigationTest : BunitContext +{ + [Fact(DisplayName = "Parent returns the component that rendered this component")] + public void Test001() + { + var cut = Render(); + + var parent = cut.FindComponent().Parent(); + + parent.ShouldNotBeNull().Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "Parent of the outermost rendered component is null")] + public void Test002() + { + var cut = Render(); + + cut.Parent().ShouldBeNull(); + } + + [Fact(DisplayName = "Root returns the outermost rendered component")] + public void Test003() + { + var cut = Render(); + + var root = cut.FindComponent().Root(); + + root.ShouldBeSameAs(cut); + } + + [Fact(DisplayName = "GetChildren returns direct child components only, in render order")] + public void Test004() + { + var cut = Render(); + + var children = cut.GetChildren(); + + children.Count.ShouldBe(2); + children[0].Instance.ShouldBeOfType(); + children[1].Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetChildren does not return grandchildren")] + public void Test005() + { + var cut = Render(); + + var children = cut.GetChildren(); + + children.Count.ShouldBe(1); + children[0].Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetChildren returns only direct children of that type")] + public void Test006() + { + var cut = Render(); + + var children = cut.GetChildren(); + + children.Count.ShouldBe(1); + children[0].ShouldBeSameAs(cut.FindComponent()); + } + + [Fact(DisplayName = "GetAncestors returns components from the closest parent to the root")] + public void Test007() + { + var cut = Render(); + + var ancestors = cut.FindComponent().GetAncestors().ToArray(); + + ancestors.Length.ShouldBe(2); + ancestors[0].Instance.ShouldBeOfType(); + ancestors[1].Instance.ShouldBeOfType(); + } +} diff --git a/tests/bunit.tests/Rendering/RenderModeTest.razor b/tests/bunit.tests/Rendering/RenderModeTest.razor index afc865b9e..ecc32b481 100644 --- a/tests/bunit.tests/Rendering/RenderModeTest.razor +++ b/tests/bunit.tests/Rendering/RenderModeTest.razor @@ -1,6 +1,3 @@ -@code{ - #if NET9_0_OR_GREATER -} @using Bunit.TestAssets.RenderModes; @inherits BunitContext @code { @@ -171,6 +168,3 @@ act.ShouldThrow(); } } -@code{ - #endif -} diff --git a/tests/bunit.tests/Rendering/RenderedComponentTest.cs b/tests/bunit.tests/Rendering/RenderedComponentTest.cs index f2ab250f4..3acd3feb0 100644 --- a/tests/bunit.tests/Rendering/RenderedComponentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedComponentTest.cs @@ -304,7 +304,7 @@ public void Test030() _ = cut.Nodes; cut.Render(ps => ps.AddChildContent("

      1

      ")); // Holding the parser's lock pauses the reader after it captured the old markup but before it caches the parsed nodes. - var parserLock = typeof(BunitHtmlParser) + var parserLock = (Lock)typeof(BunitHtmlParser) .GetField("parserLock", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(Services.GetRequiredService())!; var reader = new Thread(() => _ = cut.Nodes); diff --git a/tests/bunit.tests/Rendering/SharedDocumentTest.cs b/tests/bunit.tests/Rendering/SharedDocumentTest.cs new file mode 100644 index 000000000..8529c767c --- /dev/null +++ b/tests/bunit.tests/Rendering/SharedDocumentTest.cs @@ -0,0 +1,142 @@ +using AngleSharp.Dom; +using Bunit.Web.AngleSharp; + +namespace Bunit.Rendering; + +/// +/// Verifies that all rendered components under the same root share one +/// AngleSharp document, and that components whose markup cannot be located +/// in it fall back to their own document. +/// +public class SharedDocumentTest : BunitContext +{ + [Fact(DisplayName = "A child component's element is the same instance as the parent component's view of it")] + public void Test001() + { + var cut = Render(); + + var fromParent = cut.Find("button").Unwrap(); + var fromChild = cut.FindComponent().Find("button").Unwrap(); + + fromChild.ShouldBeSameAs(fromParent); + } + + [Fact(DisplayName = "A child component's element has the parent component's element as its parent")] + public void Test002() + { + var cut = Render(); + + var button = cut.FindComponent().Find("button"); + + button.ParentElement.ShouldNotBeNull().Id.ShouldBe("parent-form"); + } + + [Fact(DisplayName = "Nodes of parent and child components come from the same document")] + public void Test003() + { + var cut = Render(); + + var child = cut.FindComponent(); + + child.Nodes[0].Owner.ShouldBeSameAs(cut.Nodes[0].Owner); + } + + [Fact(DisplayName = "Find on a child component only matches elements rendered by that component")] + public void Test004() + { + var cut = Render(); + + var child = cut.FindComponent(); + + Should.Throw(() => child.Find("#parent-div")); + } + + [Fact(DisplayName = "Markup of a child component is unaffected by the shared document")] + public void Test005() + { + var cut = Render(); + + var child = cut.FindComponent(); + + child.Markup.ShouldStartWith("(); + var child = cut.FindComponent(); + var initialNodes = child.Nodes; + + child.Nodes.ShouldBeSameAs(initialNodes); + } + + [Fact(DisplayName = "A component whose sibling re-renders gets its element wrapper refreshed")] + public void Test007() + { + var cut = Render(); + var button = cut.FindComponent().Find("button"); + + cut.Find("#counter-button").Click(); + + // The wrapper must re-resolve into the new document instead of + // exposing a node detached from the previous parse. + button.Unwrap().Owner.ShouldBeSameAs(cut.Nodes[0].Owner); + } + + [Fact(DisplayName = "A child component rendering a inside the parent's is found")] + public void Test010() + { + var cut = Render(); + + var rows = cut.FindComponents(); + + rows.Count.ShouldBe(2); + rows[0].Find("td").TextContent.ShouldBe("one"); + rows[1].Find("td").TextContent.ShouldBe("two"); + } + + [Fact(DisplayName = "A child component rendering an