Unit Test a Service that depends on Blazor IJSRuntime

Viewed 141

I'm currently writing a razor class library. The library only contains a single Service. The purpose of the class library is to form an API between javascript and c#. Therefore I need JSInterop.

I already wrote the interface of said service, but before I start coding any implementation of it I want to write the unit tests for it.

The problem is, that I don't see a way to get my hands on an IJSRuntime object. I created the NUnit test project already and it has the following Setup:

public partial class MyServiceTests
{
    private IMyService myService;

    [SetUp]
    public void Setup()
    {
        IJSRuntime jsRuntime = null; // where do I get this from?
        myService = new MyServiceImplementation(jsRuntime);
    }
}

I need some way to access an IJSRuntime object.

It came to my mind that I would probably need a blazor WASM or Server application running for the unit tests to work. My Service will access the local storage and manage some stuff there, so I would need a website running. I tried creating those apps but sadly had no idea where to go from there.

How would I be able to run my NUnit tests successfully with an IJSRuntime?

1 Answers

I've got something similar. A possible way to solve this is with Mock.

Try to Register IJSRuntime as a dependency (Mock< IJSRuntime>). With this, you will have a reference to an object that implements the interface.

And then to "Simulate" the host you need to add:

host.AddService(jsRuntimeMock.Object);

A way to implement unit testing in blazor is here, i follow that one ant it works!

Related