Unit test a grid

Hi,

I'm creating a grid with several columns. One of them has a dropdownlist inside, and depending on the selected value, some other columns should be disabled or not.

How could I create some unit tests to validate this behavior?

Regards.


5 Replies 1 reply marked as answer

JC Jasmine Champagne February 28, 2024 09:42 AM UTC

Hey!


Oh, I totally feel your pain with trying to test the dynamic parts of a grid, especially when dropdown selections start disabling other columns. It's like you're trying to make sure everything behaves, but the grid's just laughing at you, right? Anyway, I've been down this road a few times and found a pretty solid way to tackle it using Jest and React Testing Library. They're pretty much my go-to tools for this kind of task because they let you mimic user behavior pretty closely, which is exactly what you need.


So, here’s the game plan:


First, you've got to get your grid component on the stage. If it’s feeding off some data to show those columns, make sure to have that mock data ready. It's all about setting the scene for your test.


Now, for the fun part: pretend you're the user and change that dropdown value. React Testing Library has this cool `fireEvent` function that’s perfect for this. Just find that dropdown in what you've rendered and use `fireEvent.change` to pick different options. It's like you're there, clicking away.



import { render, fireEvent } from '@testing-library/react';

import MyGridComponent from './MyGridComponent'; // Swap this with your actual component


test('changing dropdown disables columns as it should', () => {

  const { getByLabelText, getByTestId } = render(<MyGridComponent />);


  // Let's pretend to select something in the dropdown

  fireEvent.change(getByLabelText('Your Dropdown Label'), { target: { value: 'whateverYouNeedToTest' } });


  // Time to check if our expected column got disabled

  // How you check this depends on your setup. Maybe it's a class, an attribute, or something else.

  expect(getByTestId('columnTestId')).toBeDisabled(); // Just make sure this matches how you've set things up.

});

```


You'll want to run through this with each dropdown value that’s supposed to tweak the columns' enabled/disabled state. It’s all about covering your bases to make sure users don't run into surprises.


Some friendly advice:

- Think like your user: Your tests should really focus on mimicking what a user would do and expect to see. That’s your North Star.

- Build up your tests: Start with the straightforward stuff to ensure the basics work, then layer on the complexity. It helps build a safety net of tests around your component.


If you hit a snag or need more details on something, just holler. I’m here to help. Good luck with setting up those tests, and I hope this makes the process a bit smoother for you!


Cheers!



JF Juan Francisco Miranda Aguilar February 28, 2024 06:33 PM UTC

Hi and thank you very much for your so detailed answer, I really appreciate it. I'm using bUnit, but I don't know how to modify the datasource of the grid and fire the events I have defined on it.


Do you know if there is any way of accomplish a similar task with bUnit?


Regards.



MS Monisha Saravanan Syncfusion Team March 5, 2024 11:49 AM UTC

Hi Juan Francisco,


Greetings from Syncfusion.

We have prepared a simple sample with bunit test case as per your requirement by checking the enable/disable state of the dropdown list. Kindly check the below attached sample and code snippet for your reference.


We have manually selected the rows using SelectRowAsync and perform edit using StartEditAsync method. Then we have checked for the disabled state of the Dropdown using ID property and selected the value from the editable dropdown popup and once again we have checked the disabled state of the dropdownlist.


  public async Task Test1()

  {

      using var testContext = new TestContext();

          

      // Add Syncfusion Blazor service and Ignore script isolation.

      testContext.Services.AddSyncfusionBlazor();

      testContext.Services.AddOptions();

 

      // Rendering application Index component (~/Pages/Index.razor).

 

      var indexComponent = testContext.RenderComponent<Index>();

          

      // Select the row and start the edit.

 

      await indexComponent.InvokeAsync(async () => await indexComponent.Instance.Grid.SelectRowAsync(2));

      var a = indexComponent.Instance.Grid.GetSelectedRecordsAsync().Result.Count();

      indexComponent.WaitForState(() => indexComponent.Instance.Grid.GetSelectedRecordsAsync().Result.Count() == 1);

      await indexComponent.InvokeAsync( async () => await indexComponent.Instance.Grid.StartEditAsync());

 

      // Find the dropdown by ID and check for the disabled state.

 

      var IsDisabled = indexComponent.Find("[id^=\"ShipState\"]").GetAttribute("aria-disabled");

      Assert.Contains("true", IsDisabled);

 

      // Find the dropdown by ID and select the value.

 

      var compp = indexComponent.Find("[id^=\"ShipCountry\"]").ParentElement;

      Assert.Contains("e-ddl-icon", compp.Children[1].ClassName);

      Assert.True(compp.Children[1]?.ClassName.Contains("e-input-group-icon"));

        

      var dropdownlist = indexComponent.FindComponent<SfDropDownList<string,string>>();

      await dropdownlist.Instance.ShowPopup();

      var popupEle = dropdownlist.Find(".e-popup");

      Assert.Contains("e-popup", popupEle.ClassName);

      var ulEle = popupEle.QuerySelector("ul");

      Assert.Contains("e-ul", ulEle.ClassName);

      var liCollection = ulEle.QuerySelectorAll("li.e-list-item");

      liCollection[1].Click();

      Assert.Contains("Australia", dropdownlist.Instance.Value);

      

      // check for the disabled state of the dropdownlist

 

      var compval = indexComponent.Find("[id^=\"ShipState\"]").GetAttribute("aria-disabled");

      Assert.Contains("false", compval);

 

 

  }



Please let us know if you have any concerns.


Regards,

Monisha


Attachment: UnitTestWASM_540559a4.zip


JF Juan Francisco Miranda Aguilar March 5, 2024 06:33 PM UTC

Hi,


Thank you very much for the example Monisha, it is very helpful. I would also like to know if it's possible to create a similar test but with the grid configured in Batch mode, instead of Normal.


Thanks in advance.

Greetings.



PS Prathap Senthil Syncfusion Team March 6, 2024 12:45 PM UTC

Hi Juan,

We have modified the code according to your requirements for batch editing. Additionally, we have written test cases for batch editing. We performed manual edits using the grid's public method EditCellAsync and checked for the disabled state, similar to the previous approach. You can write test cases based on your specific needs here.Kindly refer to the below modified code snippet and sample for your reference.

Index.razor

<SfGrid @ref="Grid" AllowPaging="true" DataSource="@GridData" ShowColumnChooser="true" Toolbar="@(new List<string>() { "Add","Edit","Delete","Update","Cancel" })">

    <GridEvents OnCellEdit="CellEditHandler" TValue="Orders"></GridEvents>

    <GridEditSettings AllowEditing="true" AllowDeleting="true" AllowAdding="true" Mode="@EditMode.Batch"></GridEditSettings>

   

    </GridColumns>

</SfGrid>

 

@code {

    public SfGrid<Orders> Grid;

    public List<Orders> GridData { get; set; } = new List<Orders>();

    public List<string> Countries = new List<string>() { "United States", "Australia" };

    public List<string> States = new List<string>() { "New York", "Virginia", "Washington", "Queensland", "Tasmania", "Victoria" };

    public bool Enabled = false;

    public bool Isflag { get; set; } = false;

    public void ValueChange(@Syncfusion.Blazor.DropDowns.ChangeEventArgs<string, string> args)

    {

        if (args.Value == "United States")

        {

            States = new List<string>() { "New York", "Virginia", "Washington" };

        }

        else if (args.Value == "Australia")

        {

            States = new List<string>() { "Queensland", "Tasmania", "Victoria" };

        }

        Isflag = true;

        Grid.PreventRender(false);

    }

 

    public void CellEditHandler(CellEditArgs<Orders> args)

    {

        if (args.Column.Field == "ShipState" && Isflag)

        {

            Isflag = false;

            Enabled = true;

        }

        else

        {

            Enabled = false;

        }

 

    }

 

}


public class UnitTest1

    {

        [Fact]

        public async Task Test1()

        {

            using var testContext = new TestContext();

          

            // Add Syncfusion Blazor service and Ignore script isolation.

            testContext.Services.AddSyncfusionBlazor();

            testContext.Services.AddOptions();

 

            // Rendering application Index component (~/Pages/Index.razor).

 

            var indexComponent = testContext.RenderComponent<Index>();

 

            //Check if the 'shipstate' column is disabled and  Find the dropdown by ID and check for the disabled state.

 

            await indexComponent.InvokeAsync( async () => await indexComponent.Instance.Grid.EditCellAsync(2, "ShipState"));

 

            var IsDisabled = indexComponent.Find("[id^=\"ShipState\"]").GetAttribute("aria-disabled");

            Assert.Contains("true", IsDisabled);

 

 

            //Edit the shipCountry column

            await indexComponent.InvokeAsync(async () => await indexComponent.Instance.Grid.EditCellAsync(2, "ShipCountry"));

 

 

 

            // Find the dropdown by ID and select the value.

            var compp = indexComponent.Find("[id^=\"ShipCountry\"]").ParentElement;

            Assert.Contains("e-ddl-icon", compp.Children[1].ClassName);

            Assert.True(compp.Children[1]?.ClassName.Contains("e-input-group-icon"));

        

            var dropdownlist = indexComponent.FindComponent<SfDropDownList<string,string>>();

            await dropdownlist.Instance.ShowPopup();

            var popupEle = dropdownlist.Find(".e-popup");

            Assert.Contains("e-popup", popupEle.ClassName);

            var ulEle = popupEle.QuerySelector("ul");

            Assert.Contains("e-ul", ulEle.ClassName);

            var liCollection = ulEle.QuerySelectorAll("li.e-list-item");

            liCollection[1].Click();

            Assert.Contains("Australia", dropdownlist.Instance.Value);

 

            // Check if the 'shipstate' column is enabled

 

            await indexComponent.InvokeAsync(async () => await indexComponent.Instance.Grid.EditCellAsync(2, "ShipState"));

            var compval = indexComponent.Find("[id^=\"ShipState\"]").GetAttribute("aria-disabled");

            Assert.Contains("false", compval);

 

 

        }

    }

}



Regards,
Prathap S


Attachment: UnitTestModified_sample_5bf4042f.zip

Marked as answer
Loader.
Up arrow icon