1

我有一个将其客户加载到表中的 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>");

如果我单独运行测试运行良好,但当我运行所有测试时失败并出现错误

预期 tds.Count 为 2,但发现为 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",
        });
    }
}
4

1 回答 1

1

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));
于 2022-03-02T09:47:56.423 回答