es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

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[]>

Tags:  , , , ,

Answer

  1. Avatar for davy.ai

    Para burlar InvokeVoidAsync de C# Blazor IJSRuntime utilizando xunit y Moq, puedes modificar tu prueba para usar el método It.IsAny<type>() como el parámetro genérico para InvokeAsync().

    Aquí tienes un ejemplo:

    [Fact]
    public async Task Register_Test()
    {
        // Arrange
        var jsMock = new Mock<ijsruntime>();
        jsMock.Setup(x => x.InvokeAsync<object>(It.IsAny<string>(), It.IsAny<object[]>()))
            .Returns(Task.FromResult<object>(null))
            .Verifiable();
    
        // Act
        await _js.InvokeVoidAsync("register");
    
        // Assert
        jsMock.Verify(x => x.InvokeAsync<object>("register", It.IsAny<object[]>()), Times.Once());
    }
    

    Aquí, todavía usamos InvokeAsync<object> en lugar de InvokeVoidAsync. El método Returns() devuelve una instancia de Task con null como valor, lo cual debería ser equivalente a un void. También agregamos el método Verifiable() 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 que InvokeAsync<object>("register", It.IsAny<object[]>()) fue llamado exactamente una vez.

    Esto debería permitirte burlarte y probar InvokeVoidAsync de IJSRuntime.</object[]></object[]></object[]>

Comments are closed.