Reputation: 21
In my Blazor app, I am trying to test delete code, when the button is clicked, it will run the following code to display a confirmation dialog:
public async Task DeleteDocument(DocumentViewModel document)
{
bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure?");
if (confirmed)
{
... do some delete code here
}
In my test project I have this line:
_mockJsRuntime
.Setup(js => js.InvokeAsync<bool>(It.IsAny<string>(), It.IsAny<object>()))
.Returns(ValueTask.FromResult(true));
When I run the test, I get the following error:
Extension methods (here: JSRuntimeExtensions.InvokeAsync) may not be used in setup / verification expressions.
What can I do to to be able to test my DeleteDocument method?
Upvotes: 2
Views: 806
Reputation: 285
var jsInteropMock = new Mock<IJSRuntime>();
jsInteropMock.Setup(js => js.InvokeAsync<bool>(It.IsAny<string>(), It.IsAny<object[]>()))
.ReturnsAsync((string identifier, object[] args) =>
{
if (identifier == "confirm")
{
return true;
}
return false;
});
Upvotes: 0
Reputation: 1333
For you to be able to mock a method return, the mock type must be an interface or the method must be marked as abstract or virtual.
In your case, you cannot mock the extension method because it is not a virtual method. Usually the extension methods will end up calling to a method declared in the interface, in this case, you can easily check the source code here.
So you can change the setup to match the method signature declared in the IJSRuntime interface.
_mockJsRuntime
.Setup(js => js.InvokeAsync<bool>(It.IsAny<string>(), It.IsAny<object[]>()))
.Returns(ValueTask.FromResult(true));
Upvotes: 1