Table of Contents

Verifying the state of a component

The instance of a component under test is available through the Instance property on the IRenderedComponent<TComponent> type. When using the TestContext's RenderComponent<TComponent>() method, this is the type returned.

In .razor based tests, using the TestContext's Render<TComponent>(RenderFragment) method also returns an IRenderedComponent<TComponent> (as opposed to the Render(RenderFragment) method which returns the more simple IRenderedFragment).

Note

Since IRenderedComponent<TComponent> inherits from IRenderedFragment, all the markup verification techniques covered on the Verifying markup from a component page also apply 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:

IRenderedComponent<Alert> cut = 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 instances of components nested inside the component under test, use the FindComponent<TComponent>() and FindComponents<TComponent>() methods on the IRenderedComponent<TComponent> type. Suppose, for each task in the todo list, we have a <TodoList> component with <Task> components nested inside. In this case, the <Task> components can be found like this:

var cut = 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 matching component found, and the latter returning all matching components in the render tree.

Progress Telerik

Premium sponsor: Progress Telerik.

Packt

Editorial support provided by Packt.

.NET Foundation

Supported by the .NET Foundation.