Disposing components
To dispose all components rendered with a TestContext
, use the DisposeComponents
method. Calling this method will dispose all rendered components, calling any IDisposable.Dispose
or/and IAsyncDisposable.DisposeAsync
methods they might have, and remove the components from the render tree, starting with the root components and then walking down the render tree to all the child components.
Disposing rendered components enables testing of logic in Dispose
methods, e.g., event handlers, that should be detached to avoid memory leaks.
The following example of this:
var calledTimes = 0;
var cut = RenderComponent<DisposableComponent>(parameters => parameters
.Add(p => p.LocationChangedCallback, url => calledTimes++)
);
DisposeComponents();
Services.GetRequiredService<NavigationManager>().NavigateTo("newurl");
Assert.Equal(0, calledTimes);
Warning
For IAsyncDisposable
(since .net5) relying on WaitForState()
or WaitForAssertion()
will not work as a disposed component will not trigger a new render cycle.
Checking for exceptions
Dispose
as well as DisposeAsync
can throw exceptions which can be asserted as well. If a component under test throws an exception in Dispose
the DisposeComponents
will throw the exception to the user code:
RenderComponent<ExceptionInDisposeComponent>();
var act = DisposeComponents;
Assert.Throws<NotSupportedException>(act);
DisposeAsync
behaves a bit different. The following example will demonstrate how to assert an exception in DisposeAsync
:
RenderComponent<ExceptionInDisposeAsyncComponent>();
DisposeComponents();
var exception = Renderer.UnhandledException.Result;
Assert.IsType<NotSupportedException>(exception);