Between the integration tests, which see HTML only as text, and the end-to-end test, which needs a browser, there is a gap: does the booking form have its error messages at the right field? Does the week calendar show the next week after a click? Does a row of the contact list show a “–” when the company is missing? Component tests check that. They render a component without a server and without a browser, trigger its events and look at what comes out. In this lesson you write such tests with bUnit for the three components of the Kladde that have the most behavior.

bUnit

There is no tool from Microsoft for component tests. The Blazor documentation names bUnit as an example, a library that isn’t from Microsoft, is open source under the MIT license and is on nuget.org as the package bunit. bUnit renders a component with Blazor’s real renderer, turns the result into a document you can search with CSS selectors, and triggers events the way the browser would.

Only the package goes into the test project:

PowerShell
dotnet package add bunit --project tests/Kladde.Web.Tests/Kladde.Web.Tests.csproj

Since lesson 2.7.3, Kladde.Web.Tests has the Web SDK, which also compiles Razor. The tests of this lesson, though, are in ordinary .cs files; that is enough for everything the Kladde needs.

A test class inherits from BunitContext. This class brings everything with it: Render<T>(), the components’ services under Services and a fake navigation. xUnit creates a new instance of the class for every test, so each test has its own context, and cleans it up afterward. In older tutorials the class is still called TestContext and the method RenderComponent; since bUnit 2 they are called BunitContext and Render. bUnit still knows the old name TestContext, though. That becomes important as soon as a component test needs xUnit’s TestContext for its CancellationToken (solution 2).