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 returndefault(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:
A flexible, dynamic way to interact with JavaScript without strict type enforcement.
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
:
How It Works:
You pass the name of the JavaScript function (
functionName
) and any required arguments (args
) dynamically.This avoids strict binding to specific JavaScript methods or type definitions.