Verifying the State of a Component
Calling RenderComponent<TComponent>()
on a TestContext or calling GetComponentUnderTest<TComponent>() on a Fixture returns an instance of the IRenderedComponent<TComponent> type.
The IRenderedComponent<TComponent> type makes it possible to inspect the instance of the component under test (TComponent
), and trigger re-renders explicitly.
Note
Since IRenderedComponent<TComponent> inherits from IRenderedFragment, all the markup verification techniques covered on the Verifying Markup from a Component page also applies to the IRenderedComponent<TComponent> type.
Inspecting the Component Under Test
The Instance property on the IRenderedComponent<TComponent> type provides access to the component under test. For example:
using var ctx = new TestContext();
IRenderedComponent<Alert> cut = ctx.RenderComponent<Alert>();
Alert alert = cut.Instance;
// Assert against <Alert /> instance
Warning
While it is possible to set [Parameter]
and [CascadingParameter]
properties directly through the Instance property on the IRenderedComponent<TComponent> type, doing so does not implicitly trigger a render and the component life-cycle methods are not called.
The correct approach is to set parameters through the SetParametersAndRender()
methods. See the Triggering a Render Life Cycle on a Component page for more on this.
Finding Components in the Render Tree
To get the instance of components nested inside the component under test, use the
FindComponent<TComponent>()
and FindComponents<TComponent>()
methods on the IRenderedComponent<TComponent> type. Suppose we have a <TodoList>
component with <Task>
components nested inside for each task in the todo list. In this case, the <Task>
components can be found like this:
using var ctx = new TestContext();
var cut = ctx.RenderComponent<TodoList>(parameter => parameter
.Add(p => p.Tasks, new [] { "Task 1", "Task 2" })
);
var tasks = cut.FindComponents<Task>();
Assert.Equal(2, tasks.Count);
Both the FindComponent<TComponent>()
and FindComponents<TComponent>()
methods perform a depth-first search of the render tree, with the first method returning only the first found matching component, and the latter returning all matching components in the render tree.
Both the FindComponent<TComponent>()
and FindComponents<TComponent>()
methods performs a depth-first search of the render tree, with the first method returning only the first found matching component, and the latter returning all matching components in the render tree.