Testing a Blazored Modal with bUnit

blazor wasm

I recently needed to add unit tests on a modal window that uses the library Blazored.Modal. As it is a component, I used the library bUnit for my tests. On the other hand, I encountered some problems when setting up the tests, so I thought I would share with you what I did to simplify my life.

Blazored Modal

For those who do not know the library, it is developed by Chris Sainty, one of the best references on Blazor in my opinion. It allows you to make modal windows easily, with a service that you can simply call to display the window.


bUnit is a library which is currently available in version preview, which allows unit testing of our Blazor components. We can therefore, for example, check that certain HTML tags will be present under certain conditions, or for example that the click of a button will indeed trigger an action.

In context

In my case, I wanted to test that the submit of my modal window was indeed going to trigger the sending of an action on the Dispatch of Fluxor, the library of state management that I use in my project. So the function looked like this:

So I wrote my test, taking care to inject the IDispatcher of Fluxor and thus verify it. On this image we only see the test, the injection of the mock being done at the level of the constructor.

On the other hand, on execution, the test did not work, mentioning a ArgumentException which seemed to be connected to a CascadingValue. By digging into the source of the problem, I came to the conclusion that the modal window, being normally used inside a component cascading that Blazored.Modal provides us with, couldn't work without being in that same context. So I created myself an abstract class from which I can inherit for my modal tests, which allows the component to be encapsulated inside everything necessary in the context of Blazored.Modal for it to work. In the end, the only difference for the test is the method we call to render the component:


So here is the class you can use for your projects to make it easier for you to test modal windows from Blazored.Modal. It puts everything in place so that the modal window is rendered in the same context as if it were used in your application. Two methods exist, the difference being that one of them allows us to add parameters to our components.


I hope this simple class will save you some time in your next modal window unit tests. If you have any comments or questions, whether about this class, Blazored.Modal or even bUnit, please let me know in the comments!


Author: Bruno

By day, I am a developer, team leader and co-host of the Bracket Show. By evening, I am a husband and the father of two wonderful children. The time I have left after all of this I spend trying to get moving, playing and writing video game reviews, as well as preparing material for the Bracket Show recordings and for this blog. Through it all, I am also passionate about music and microbreweries.