bunit 在断言字段之前等待 OnInitializedAsync 完成

bunit wait until OnInitializedAsync finishes before Asserting fields

我有一个将其客户加载到 table 的 Blazor 服务器组件,它在 OnInitializedAsync 方法中获取客户。有没有办法等待 OnInitializedAsync 完成?

组件

<table>
    <thead>
    <tr>
        <th>Name</th>
        <th>Id</th>
    </tr>
    </thead>
    <tbody>
    @foreach (var customer in _customers)
    {
        <tr>
            <td>@customer.Name</td>
            <td>@customer.Id</td>
        </tr>
    }
    </tbody>
</table>

@code {
    IEnumerable<Customer> _customers = new List<Customer>();

    protected override async Task OnInitializedAsync()
    {
        _customers = await _customerService.GetCustomersAsync();
        StateHasChanged();
    }
}

我的测试需要等到 运行 我的测试完成。

var ctx = new TestContext();
ctx.Services.AddHttpContextAccessor();
ctx.Services.AddScoped<ICustomerService, CustomerServiceMock>();
var component = ctx.RenderComponent<Customers>();

var tableRows = component.FindAll("tr");
var buttons = component.FindAll("a");
var addButton = buttons.FirstOrDefault(b => b.OuterHtml.Contains("Add"));

component.WaitForAssertion(() => component.FindAll("td").Count.Equals(2));

var tds = component.FindAll("td");
var ths = component.FindAll("th");

// ASSERT
tableRows.Should().NotBeNull();
addButton.Should().NotBeNull();
tds.Count.Should().Be(2);
ths.Count.Should().Be(2);
ths[0].OuterHtml.Should().Be("<th>Name</th>");
ths[1].OuterHtml.Should().Be("<th>Id</th>");
tds[0].OuterHtml.Should().Be("<td>Customer XXX</td>");
tds[1].OuterHtml.Should().Be("<td>999</td>");

如果我单独 运行 测试 运行 没问题,但是当我 运行 所有测试连同错误

时失败

Expected tds.Count to be 2, but found 0.

模拟

public class CustomerServiceMock : ICustomerServiceMock
{
    public async Task<IEnumerable<Customer>> GetCustomersAsync()
    {
        return new List<Customer>
        {
            await GetCustomer()
        };
    }

    private static async Task<Customer> GetCustomer()
    {
        return await Task.Run(() => new Customer
        {
            Id = 999,
            Name = "Customer XXX",
        });
    }
}

WaitForAssertion() 需要一些抛出而不是返回 false 的东西。

//component.WaitForAssertion(() => component.FindAll("td").Count.Equals(2));

应该变成

component.WaitForAssertion(() => component.FindAll("td").Count.Should().Be(2));

或(更好)使用 WaitForState()

component.WaitForState(() => component.FindAll("td").Count.Equals(2));