Live Chat Icon For mobile
Live Chat Icon

How do I unit test a Blazor component?

Platform: Blazor| Category : Testing, General

Unit testing is a level of software testing that is used by developers to ensure that the implemented logic meets the requirements and behaves as expected. The following example uses the bUnit testing library for Blazor components to write comprehensive and stable unit test cases. It allows you to write test cases in C# or Razor syntax to verify outcomes with semantic HTML diffing and comparison logic.

Create a simple Blazor Server/WebAssembly application.
In Visual Studio 2019, right-click on the project solution and select the Add > New Project option.


 Add-New-project-in-VS-2019
Select NUnit Test Project (.NET Core) and click Next button.

NUnit Test Project
Enter the project name and then click Create button. The created project will be displayed like the following.

Created Project
Open the NuGet manager for BlazorTest and search with the keyword bunit.web. The result will be displayed as seen in the following screenshot. Select bunit.web and install it.

Nuget Manager Window
Right-click on BlazorTest project dependencies and add the project reference BlazorServerApp.
Now, write a test case for a Razor component.
Add a Razor component to your Blazor project.

[Index.razor]

 @page "/"
 
<h3>Hello World</h3>
 
<button class="btn btn-primary" @onclick="OnButtonClick">Ping Me</button>
 
@if (IsVisible)
{
    <h5>Blazor component is clicked.</h5>
}
 
@code {
 
    public bool IsVisible { get; set; }
    protected void OnButtonClick()
    {
        IsVisible = true;
    }
}
Add the following test cases in your created test project file [UnitTest1.cs] to test the Blazor components.

[UnitTest1.cs]

using NUnit.Framework;
using Bunit;
 
namespace TestProject1
{
    public class Tests
    {
        [SetUp]
        public void Setup()
        {
        }
 
        [Test]
        public void Test1()
        {
            // Arrange
            using var context = new Bunit.TestContext();
 
            // Act
            var cut = context.RenderComponent<BlazorServerApp.Pages.Index>();
            cut.Find("button").Click();
 
            // Assert
            cut.Find("h5").MarkupMatches("<h5>Blazor component is clicked.</h5>");
        }
    }
}
Then select the View > Test Explorer options in Visual Studio 2019 and run the test.
Now you will see the list of test methods. The test run is successful, and the test case passes. You can also alter the test case if it fails.

Refer to “Unit test a Blazor component” for more details and download the sample here.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.