简体   繁体   English

Blazor 组件单元测试的 Mocking IJSRuntime

[英]Mocking IJSRuntime for Blazor Component unit tests

Following this prototype for unit testing I've ran into a problem when using JS interop.按照这个原型进行单元测试,我在使用 JS 互操作时遇到了问题。

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

Just adding a component that uses IJSRuntime will cause the following exception只需添加一个使用 IJSRuntime 的组件就会导致以下异常

System.InvalidOperationException: Cannot provide a value for property 'JsRuntime' on type 'Application.Components.MyComponent'. System.InvalidOperationException:无法为类型“Application.Components.MyComponent”的属性“JsRuntime”提供值。 There is no registered service of type 'Microsoft.JSInterop.IJSRuntime'.没有“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. JS 互操作没有做任何有趣的事情,它只是一个专注于元素的 void function - 我不关心测试它,我只想能够继续为组件本身编写测试。

How can I use Moq to mock IJSRuntime?如何使用 Moq 模拟 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我仍然得到异常

host.AddService(jsRuntimeMock);

registers Mock<IJSRuntime> as a dependency.Mock<IJSRuntime>注册为依赖项。

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.使用Mock<T>属性ObjectIJSRuntime注册为依赖项,其中包含对实现接口的 object 的引用。

Like this:像这样:

host.AddService(jsRuntimeMock.Object);

Microsoft uses a lot of internal Singletons and therefore having test on application Level very very difficult and you should replace all Default Services like IJSRuntime, NavigationManager and NavigationInterceptor. Microsoft 使用大量内部单例,因此在应用程序级别进行测试非常非常困难,您应该替换所有默认服务,如 IJSRuntime、NavigationManager 和 NavigationInterceptor。 I hope in the next preview there will be an easy way to create a unittest methods and simulate the browser.我希望在下一次预览中会有一种简单的方法来创建单元测试方法并模拟浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM