Blazor Webassembly Bunit test changing blazorCulture?

Viewed 34

I am trying to test the blazorCulture change using Bunit Test but I am unable to get and set the blazorCulture.

Below code works in the actual blazor Wasm application but not working within a Bunit

var js = Services.GetRequiredService<IJSRuntime>();
            var result = await js.InvokeAsync<string>("blazorCulture.get");

            if (result != null)
            {
                CultureInfo.CurrentCulture = new CultureInfo(result);
            }
            else
            {
                CultureInfo.CurrentCulture = new CultureInfo("de-De");
                await js.InvokeVoidAsync("blazorCulture.set", "de-De");
            }

What is the way to change the Rendered Components culture and language using Bunit test?

1 Answers

You are invoking JavaScript, which bUnit does not run, it runs entirely in C#. However, bUnit does come with a fake JSInterop implementation, that you can use to verify that you have made the correct calls to your blazorCulture.get and blazorCulture.set methods.

In your test, you can write something like this:

// arrange
var ctx = new TestContext();
ctx.JSInterop.Setup<string>("blazorCulture.get").SetResult("da-DK");
ctx.JSInterop.SetupVoid("blazorCulture.set").SetVoidResult();

// act
...

// assert
var invocations = ctx.JSInterop.Invocations["blazorCulture.set"];
var argument = invocations[0].Arguments[0]; // assumes only one invocation with one argument
Assert.Equal("de-De", argument);

Learn more here: https://bunit.dev/docs/test-doubles/emulating-ijsruntime.html

Related