Blazor test InputDate binding with bUnit
Asked Answered
D

1

6

I have a Blazor page and want to do unittesting via bUnit with xUnit. I want change input value and verify result.

With InputText everything works fine. With InputNumber I can pass only string. If I pass number value stays the same.

My problem with InputDate binding: I can't change value properly. I've tried :

cut.Find("#date input").Change(myDate.Date);

The value stays the same(unchanged).

cut.Find("#date input").Change(myDate.Date.ToString());

or

cut.Find("#date input").Change(myDate.Date.ToString("dd/MM/yyyy"));

The value is invalid, validation-message:The date field must be a date.

My Blazor-page:

<EditForm Model="this">
    <DataAnnotationsValidator />
    <div id="name">
        <label>@name</label>
        <ValidationMessage For="@(() => this.name)" />
        <InputText @bind-Value="this.name"/>
    </div>
    <div id="date">
        <label>@date</label>
        <ValidationMessage For="@(() => this.date)" />
        <InputDate @bind-Value="this.date" />
    </div>
    <div id="num">
        <label>@num</label>
        <ValidationMessage For="@(() => this.num)" />
        <InputNumber @bind-Value="this.num" max="23" min="0" />
    </div>
</EditForm>
@code{
    private DateTime date = DateTime.Today;
    private string name = "n";
    private int num = 11;
}

and my UnitTest:

 [Fact]
    public void Test1()
    {
        DateTime myDate = new DateTime(2020, 11, 15, 15, 0, 0);
        string myName = "bbb";
        using var ctx = new TestContext();

        // Act
        var cut = ctx.RenderComponent<BlazorInputDate.Pages.Index>();
        cut.Find("#name input").Change(myName);
        cut.Find("#date input").Change(myDate.Date);
        cut.Find("#num input").Change(myDate.Hour.ToString());

        // Assert
        Assert.Equal(myName, cut.Find("#name label").InnerHtml);
        Assert.Equal(myDate.Hour.ToString(), cut.Find("#num label").InnerHtml);
        Assert.Equal(myDate.ToString(), cut.Find("#date label").InnerHtml);
    }

How cat I test InputDate binding?

Dynamite answered 25/11, 2020 at 16:25 Comment(0)
D
8

It was wrong date format.

        cut.Find("#date input").Change(myDate.Date.ToString("yyyy-MM-dd"));

works for me.

Dynamite answered 26/11, 2020 at 0:29 Comment(1)
In tests like this I would tend to use strings to avoid this sort of issue: e,g. const string dateText = "15/11/2020" for setting the control. It also avoids localization issues - your PC's context might be ru-RU for example, but the server is en-USSpraddle

© 2022 - 2024 — McMap. All rights reserved.