Search code examples
unit-testingmockingnunitblazorbunit

How to mock out a Blazor component rendered within another component?


Suppose I have the below Parent.razor component:

<div>
    <span>Below is a child component.</span>
    <Child/>
</div>

Where Child is a very complex component Child.razor.

If I want to unit-test Parent.razor, how do I mock out <Child/> so that the test focuses on the Parent component alone? What libraries do I use?


Solution

  • Unless you design your Parent component such that it's Child components can be replaced at runtime (e.g. through a RenderFragment parameter), you cannot replace a component at runtime, and thus not mock it.

    There is a change coming in .net 5 that will allow bUnit to do it, but for the current version of Blazor it's not possible.