3

Imagine I have the following class and I want to test both, the firstRender = false and the firstRender=true "path". For this sake I am using bunit and xunit.

public class ToTest {
    protected async override void OnAfterRender(bool firstRender)
    {
         if(firstRender)
         {
              //do stuff
         }
         else
         {
              //do other stuff
         }
    }
}
public class TestClass : TestContext
{
    
    [Fact]
    public void Test()
    {
        //Arrange stuff before this method
        var cut = RenderComponent<News>(parameters => parameters
        .Add(p => p.authenticationStateTask, stateProvider.GetAuthenticationStateAsync()));
    }

}

Is there a way to set the firstRender-Variable of the OnAfterRender method in bunit testing? Do I have to adjust the RenderComponent-Parameters?

3r1c
  • 376
  • 5
  • 20

1 Answers1

2

bUnit allows you to perform multiple renders of a component under test. The first render will always have firstRender set to true, and any additional renders will have it set to false, just like the regular Blazor runtime.

For example:

public class TestClass : TestContext
{
    
    [Fact]
    public void Test()
    {
        // First render, where firstRender is true
        var cut = RenderComponent<News>(parameters => parameters
           .Add(p => p.Param, "Bar"));

       // Second render, where firstRender is false
       cut.Render();

       // Third render, with new parameters set during the render life-cycle 
       // and where firstRender is also false
       cut.SetParametersAndRender(parameters => parameters
           .Add(p => p.Param, "Foo"));
    }

}

Learn more here: https://bunit.dev/docs/interaction/trigger-renders.html

Dharman
  • 30,962
  • 25
  • 85
  • 135
Egil Hansen
  • 15,028
  • 8
  • 37
  • 54