Unable to get data from mocked HttpClient during OnInitializedAsync #255
-
|
Thanks for the wonderful library. I've just started using it. I'm having issues waiting for a response from a mocked The class is like this: [Inject]
protected HttpClient Http { get; set; }
private Data.Image image;
protected override async Task OnInitializedAsync()
{
image = await Http.GetFromJsonAsync<Data.Image>("api/image");
}The view: @if (image != null)
{
<h1 class="text-6xl">@image.Title</h1>
}My test is like this: public class ImageOfDayTest
{
[Fact]
public void ImageOfDayComponentRendersCorrectly()
{
using var ctx = new TestContext();
var mockedHttpClient = ctx.Services.AddMockHttpClient();
mockedHttpClient.When("/api/image").RespondJson(GetImage());
var cut = ctx.RenderComponent<Index>();
cut.WaitForState(() => cut.Find("h1").TextContent.Equals("My Sample Image"));
cut.WaitForAssertion(() =>
Assert.Equal("My Sample Image", cut.Find("h1").TextContent));
}
private Data.Image GetImage()
{
// returns a hard-coded object...
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
|
Hi Dave Thanks for the kind words. The HttpClient mock from the docs is not really battle hardened, so I cannot guarantee that it behaves correctly in all scenarios, and its shown more as proof-of-concept. Anyway, disclaimer aside, it looks as if you are setting up the mock to handle Otherwise your test looks fine. Related, I do advice not to depend explicitly on HttpClient in your components. Create an abstraction instead, e.g. Hope this helps. |
Beta Was this translation helpful? Give feedback.
Hi Dave
Thanks for the kind words.
The HttpClient mock from the docs is not really battle hardened, so I cannot guarantee that it behaves correctly in all scenarios, and its shown more as proof-of-concept. Anyway, disclaimer aside, it looks as if you are setting up the mock to handle
/api/imagebut in the component you are querying for"api/image. That might be it.Otherwise your test looks fine.
WaitForStatebeforeWaitForAssertionwont make a difference.Related, I do advice not to depend explicitly on HttpClient in your components. Create an abstraction instead, e.g.
IImageStore. That will not only make writing tests much easier, but also allow you to add caching and other things down …