Mock IJSRuntime InvokeVoidAsync Fingir IJSRuntime InvokeVoidAsync
Quiero simular InvokeVoidAsync
desde C# Blazor IJSRuntime
usando xunit
y Moq
. Hasta ahora tengo una función simple para probar que llama await _js.InvokeVoidAsync("register")
, donde _js
es un objeto de tipo IJSRuntime
.
Mi prueba se ve así:
[Fact]
public async Task Register_Test()
{
var jsMock = new Mock<ijsruntime>();
jsMock.Setup(x => x.InvokeAsync<object>(It.IsAny<string>(), It.IsAny<object[]>())).Returns(new ValueTask<object>());
...
jsMock.Verify(x => x.InvokeAsync<bool>("register"), Times.Once());
}
Tenga en cuenta que no llamo a InvokeVoidAsync
directamente como se indica aquí y estoy tratando de aplicar la solución de aquí que describe cómo utilizar InvokeAsync<tipo>
.
Esta prueba se compila, pero durante la ejecución obtengo un error que dice:
System.InvalidCastException : No se puede convertir el objeto del tipo 'System.Threading.Tasks.ValueTask`1[System.Object]' al tipo 'System.Threading.Tasks.ValueTask`1[Microsoft.JSInterop.Infrastructure.IJSVoidResult]'.
¿Cómo puedo llamar y probar InvokeVoidAsync
desde IJSRuntime
?</object[]>
davy.ai
Para burlar
InvokeVoidAsync
de C# BlazorIJSRuntime
utilizandoxunit
yMoq
, puedes modificar tu prueba para usar el métodoIt.IsAny<type>()
como el parámetro genérico paraInvokeAsync()
.Aquí tienes un ejemplo:
Aquí, todavía usamos
InvokeAsync<object>
en lugar deInvokeVoidAsync
. El métodoReturns()
devuelve una instancia deTask
con null como valor, lo cual debería ser equivalente a un void. También agregamos el métodoVerifiable()
a la configuración para asegurarnos de que la burla será verificada en la aserción.Luego, en la prueba en sí, llamamos a
_js.InvokeVoidAsync("register")
y verificamos queInvokeAsync<object>("register", It.IsAny<object[]>())
fue llamado exactamente una vez.Esto debería permitirte burlarte y probar
InvokeVoidAsync
deIJSRuntime
.</object[]></object[]></object[]>