Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking IJSRuntime for Blazor Component unit tests

Following this prototype for unit testing I've ran into a problem when using JS interop.

[Test]
public void ExampleTest()
{
    var component = host.AddComponent<MyComponent>();
}

Just adding a component that uses IJSRuntime will cause the following exception

System.InvalidOperationException : Cannot provide a value for property 'JsRuntime' on type 'Application.Components.MyComponent'. There is no registered service of type 'Microsoft.JSInterop.IJSRuntime'.

The JS interop isn't doing anything of interest, it's just a void function that focuses an element - I don't care about testing it, I just want to be able to proceed with writing tests for the component itself.

How can I use Moq to mock IJSRuntime?

When I try something like

[Test]
public void ExampleTest()
{
    var jsRuntimeMock = new Mock<IJSRuntime>();

    host.AddService(jsRuntimeMock);

    var component = host.AddComponent<MyComponent>();
}

I still get the exception

like image 602
p3tch Avatar asked Oct 28 '19 10:10

p3tch


People also ask

Is mocking necessary in unit testing?

Mocking is a very popular approach for handling dependencies while unit testing, but it comes at a cost. It is important to recognize these costs, so we can choose (carefully) when the benefits outweigh that cost and when they don't.

What can be mocked with MOQ?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.

What mocking frameworks have you used for unit testing?

Many mocking frameworks for Java code work in combination with JUnit and other popular unit testing frameworks, and are great depending on your specific needs. Two of the most widely used are Mockito and PowerMock. Mockito is useful for all but the most complicated cases, for which you can use PowerMock instead.


1 Answers

host.AddService(jsRuntimeMock);

registers Mock<IJSRuntime> as a dependency.

No classes in the implementation (outside of a test assembly) should have such a dependency but it's a common error to make.

Register IJSRuntime as a dependency using the Mock<T> property Object, which contains a reference to an object that implements the interface.

Like this:

host.AddService(jsRuntimeMock.Object);
like image 153
Tewr Avatar answered Oct 26 '22 08:10

Tewr