JSinterop in Blazor

Posted by Hon Lee on April 09, 2025

UsingJSInterop in C# is a useful coding usage especially in Acceptance testing, it's typically used in Blazor or other .NET applications to allow interoperability between JavaScript and C#. This is incredibly useful for scenarios where you need to call JavaScript functions from C# code or vice versa.

Strict vs Loose mode in JSInterop

bUnit's JSInterop can run in two modes, strict or loose:

  • Loose mode configures the implementation to just return the default value when it receives an invocation that has not been explicitly set up, e.g. if a component calls InvokeAsync<int>(...) the mock will simply return default(int) back to it immediately.

  • Strict mode configures the implementation to throw an exception if it is invoked with a method call it has not been set up to handle explicitly. This is useful if you want to ensure that a component only performs a specific set of IJSRuntime invocations.

"Loose" Approach in JSInterop

When you say "loose," it might mean you're looking for:

  1. A flexible, dynamic way to interact with JavaScript without strict type enforcement.

  2. Or a less structured, lightweight setup compared to strongly typed bindings.

Dynamic JSInterop Example

Here’s how you could achieve a flexible approach using IJSRuntime:

csharp
using Microsoft.JSInterop;

public class JavaScriptService
{
    private readonly IJSRuntime _jsRuntime;

    public JavaScriptService(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    public async Task CallJavaScriptFunctionAsync(string functionName, params object[] args)
    {
        await _jsRuntime.InvokeVoidAsync(functionName, args);
    }
}

How It Works:

  1. You pass the name of the JavaScript function (functionName) and any required arguments (args) dynamically.

  2. This avoids strict binding to specific JavaScript methods or type definitions.