Unit tests

Just a general question: how to write unit tests for blazor pages using your components? For example, if I create an SfGrid with an SfDataManager inside, how can I write isolated unit tests for this page? Thanks in advance.

18 Replies 1 reply marked as answer

JP Jeevakanth Palaniappan Syncfusion Team November 10, 2020 09:42 AM UTC

Hi Andrea, 
Greetings from Syncfusion support. 
Based on your request, we have prepared a simple test case sample for your reference in which we have tested for basic grid rendering in the Paging component. 
Please refer the below code snippet and the sample for more information. 
Paging.razor 
@inherits GridTestBase 
 
    <SfFixture @ref="fixture" Test="GridBasicRendering" Description="Flat grid with data source and column"> 
        <ComponentUnderTest> 
            <SfGrid DataSource="GenerateOrderData()" AllowPaging="true"> 
                <GridColumns> 
                    <GridColumn Field="@nameof(Order.OrderID)" Width="150"></GridColumn> 
                    <GridColumn Field="@nameof(Order.CustomerID)" Width="150"></GridColumn> 
                    <GridColumn Field="@nameof(Order.Freight)" Width="150" Format="c2"></GridColumn> 
                </GridColumns> 
                <GridEvents TValue="Order" DataBound="DataBound"></GridEvents> 
            </SfGrid> 
        </ComponentUnderTest> 
    </SfFixture> 
  @code 
  { 
      SfFixture fixture { get; set; } 
      bool _canAssert = false; 
      void GridBasicRendering(Fixture fixture) 
      { 
          var cut = fixture.GetComponentUnderTest<SfGrid<Order>>(); 
 
          Assert.True(12 == cut.FindAll(".e-row").Count, "Number of rows generated properly"); 
          Assert.True(3 == cut.Find(".e-row").Children.Count(), "Number of cells generated properly"); 
          Assert.True(12 == cut.Instance.CurrentViewData.Count(), "CurrentViewData count is proper"); 
          _canAssert = true; 
          cut.FindComponent<SfPager>().FindAll(".e-link").ElementAt(1).Click(); 
      } 
 
      void DataBound() 
      { 
          if (_canAssert) { 
              _canAssert = false; 
              var cut = fixture.GetComponentUnderTest<SfGrid<Order>>(); 
              Assert.True(8 == cut.FindAll(".e-row").Count, "On paging rows refreshed properly"); 
              Assert.True(8 == cut.Instance.CurrentViewData.Count(), "On paging current view data changed properly"); 
          } 
      } 
  } 
 





 

Please get back to us if you need further assistance. 

Regards, 
Jeevakanth SP 


Marked as answer

AB Andrea Bioli November 10, 2020 03:30 PM UTC

Jeevakanth,
    thank you very much for your sample code, it's very useful, because I see many important and interesting details.
It doesn't totally solve my problem, anyway, so I try to explain it better.
What is needed, in the unit tests, for a real business enterprise application, is to be able to demonstrate, for example, that a page delivers an intended behaviour.
The simplest and more powerful use for the SfGrid is to be tied to an SfDataManager, where data is taken remotely. So let's imagine a page where I use an SfGrid, with an SfDataManger inside, used to query a remote source.
In that case, usually, the developer organizes code such that he/she can mock the HttpClient, or whatever is used to query remotely a web service.
So, probably, the real question I'm asking is: is it possible to intercept, or mock, the requests sent from inside an SfDataManager used for remote queries? Eventually, how?
Thanks anyway, as I said the code you sent me is really interesting, it should be added to the general examples: every developer is interested in testing!
Andrea



JP Jeevakanth Palaniappan Syncfusion Team November 13, 2020 03:42 AM UTC

Hi Andrea, 

We suggest you to refer the below links to achieve your requirement. 


Please get back to us if you need further assistance. 

Regards, 
Jeevakanth SP. 



AB Andrea Bioli November 29, 2020 11:35 AM UTC

I don't see how to find (and substitute) the HttpClient with my mocked implementation...


JP Jeevakanth Palaniappan Syncfusion Team December 7, 2020 03:49 AM UTC

Hi Andrea, 

We have seen the codes you shared in your another forum (https://www.syncfusion.com/forums/160215/unable-to-mock-the-response-to-an-sfdatamanager ) and we understand that you are facing trouble while mock testing the data returned from SfDatamanager. The data is returned in form of result and count from DataManager.  please find the below code snippet to resolve your issue. 

MockHttpMessageHandler mock = ctx.Services.AddMockHttpClient("https://localhost:44351");  
            List callResult = new()  
            {  
                new Friend { Id = 1.ToGuid(), Name = "Andrea Bioli", City = "Rome", Kind = Friend.RelationshipKind.Good, Pets = new List() },  
                new Friend { Id = 2.ToGuid(), Name = "Andrea Bioli", City = "Rome", Kind = Friend.RelationshipKind.Good, Pets = new List() }  
            };  
            HttpResponseMessage msg = new(HttpStatusCode.OK)  
            {  
                Content = JsonContent.Create(JsonSerializer.Serialize(new { result = callResult, count = callResult.Count }))  
            };  
            mock.When("/api/friends/friends-for-grid").Respond(req => msg);  

Please get back to us if you have further queries. 

Regards, 
Jeevakanth SP. 



AB Andrea Bioli December 7, 2020 07:14 AM UTC

Thanks, but it still gives an error:

Error converting value "{"result":[{"Id":"00000000-0000-0000-0000-000000000001","Name":"Andrea Bioli","City":"Rome","Kind":3,"Pets":[],"NPets":0},{"Id":"00000000-0000-0000-0000-000000000002","Name":"Andrea Bioli","City":"Rome","Kind":3,"Pets":[],"NPets":0}],"count":2}" to type 'Syncfusion.Blazor.Data.UrlResult`1[DoNothing.Shared.Friend]'. Path '', line 1, position 446.


JP Jeevakanth Palaniappan Syncfusion Team December 10, 2020 02:01 PM UTC

Hi Andrea, 

We are sorry that the provided solution not works at your end. So could you please share us the issue reproducing sample which will be helpful for us to validate the issue and provide you with a better solution as early as possible. 

Regards, 
Jeevakanth SP. 



AY abhishek yadav January 4, 2022 09:12 AM UTC

<ComponentUnderTest> Is unrecognized for sftabs in my blazor code. Is there any specific nuget package for this? Please suggest me



VN Vignesh Natarajan Syncfusion Team January 5, 2022 01:04 PM UTC

Hi Abhishek,  
 
Thanks for contacting Syncfusion support.  
 
Query: “<ComponentUnderTest> Is unrecognized for sftabs in my blazor code. Is there any specific nuget package for this? Please suggest me 
 
Before proceeding further with your requirement, we need some more details about the issue you are facing. So kindly share the following details.  
 
  1. Are you facing issue while SfTab component inside the ComponentUnderTest component test case?
  2. Are there any build error in the project.
  3. Share more details about the issue you are facing.
 
Above requested details will be very helpful for us to validate to validate the reported query at our end an provide solution as early as possible.  
 
Regards, 
Vignesh Natarajan  



AY abhishek yadav replied to Vignesh Natarajan January 10, 2022 08:56 AM UTC

My SF tab components were not rendered while testing



SK Satheesh Kumar Balasubramanian Syncfusion Team January 11, 2022 02:47 PM UTC

Hi Abhishek, 
  
We have prepared sample to test unit testing for SfTab. 
Index.razor: 
@using Syncfusion.Blazor.Navigations 
@using Syncfusion.Blazor.Inputs 
  
<SfTab OverflowMode="@OverflowMode.Popup" HeaderPlacement="@HeaderPosition.Top" LoadOn="ContentLoad.Init"> 
    <TabItems> 
        <TabItem> 
            <ChildContent> 
                <TabHeader Text="Informations" IconCss="e-tabheader-wizard-step1"></TabHeader> 
            </ChildContent> 
            <ContentTemplate> 
                <div id="informations"> 
                    <SfTextBox /> 
                    <div>Hey, I should be generated</div> 
                </div> 
            </ContentTemplate> 
        </TabItem> 
    </TabItems> 
</SfTab> 
  
UnitTest1.cs: 
using System.Threading.Tasks; 
using BlazorApp1.Pages; 
using Bunit; 
using NUnit.Framework; 
  
namespace TestProject 
{ 
    public class UnitTest1 : MyTestContext 
    { 
        [Test] 
        public async Task TestMethod1() 
        { 
            var cut = RenderComponent<Index>(); 
            await Task.Delay(1000); 
            Assert.IsTrue(cut.Markup.Contains("Hey, I should be generated")); 
        } 
    } 
} 
  
Kindly try the above sample and let us know if this meets your requirement. 
  
Regards, 
Satheesh Kumar B 



AY abhishek yadav replied to Satheesh Kumar Balasubramanian January 14, 2022 12:44 PM UTC

The above solution didn't work 



SK Satheesh Kumar Balasubramanian Syncfusion Team January 17, 2022 12:39 PM UTC

Hi Abhisek, 
  
Before proceeding further with your requirement, we need some more details about the issue you are facing. So kindly share the following details. 
  • How you are rendering SfTab and writing unit test cases?
  • Replicate the issue in above shared project
  • Share all tab related code snippets and unit test cases with package version details
  • Share issue depicting image (or) video

Regards, 
Satheesh Kumar B 



AY abhishek yadav January 18, 2022 10:21 AM UTC

Hi,

Please find the attached zip file of the project for sftab unit testing.


Attachment: SfTabsunitTesting_486cd29b.zip


SK Satheesh Kumar Balasubramanian Syncfusion Team January 19, 2022 01:03 PM UTC

Hi Abhishek, 
  
Tab is rendered properly in your shared project. We have included test case to check the tab header and content is rendered properly in unit testing. 
  
  
UnitTest1.cs:   
using Bunit; 
using System; 
using Xunit; 
using Xunit; 
using SFTabsDemoTest; 
using SFTabsDemo.Pages; 
using Syncfusion.Blazor; 
using System.Threading.Tasks; 
  
namespace SFTabsDemoTest 
{ 
    public class UnitTest1 : TestContext 
    { 
        public void Setup() 
        { 
            Services.AddSyncfusionBlazor(options => { 
                options.IgnoreScriptIsolation = true; 
            }); 
        } 
  
            [Fact] 
        public async Task IsPopulate() 
        { 
            Setup(); 
            var renderedComponent= RenderComponent<SFTabsDemo.Pages.Index>(); 
            await Task.Delay(1000); 
            //renderedComponent.MarkupMatches("Tab1"); 
            Assert.Equal("Tab1", renderedComponent.Find("." + "e-toolbar-item").TextContent); 
            Assert.Equal("Tab2", renderedComponent.FindAll("." + "e-toolbar-item")[1].TextContent); 
            Assert.Contains("Hey, I should be generated", renderedComponent.Markup); 
            //line 27 shows an error that "text is missing" because tab1 and tab2 is not rendered 
        } 
        
    } 
} 
  
 
  
 
  
Kindly try the above project and let us know if this meets your requirement. 
  
Regards, 
Satheesh Kumar B 



AY abhishek yadav January 24, 2022 10:04 AM UTC

Hi,

The solution has rendered the data from the first tab correctly, but for the second tab or the third tab, the data is not rendered. Also the unit tests for buttons do not work for onclick event.



SK Satheesh Kumar Balasubramanian Syncfusion Team January 25, 2022 02:21 PM UTC

Hi Abhishek, 
  
The solution has rendered the data from the first tab correctly, but for the second tab or the third tab, the data is not rendered. 
  
We suspect that you need to render all tab item content at initial load. You can set ContentLoad.Init to the property LoadOn to load all tab item content at initial load. 
  
  
Index.razor:    
<div class="col-lg-12 control-section"> 
    <div class="e-sample-resize-container"> 
        <SfTab @ref="Tab" CssClass="BlazorTab" LoadOn="ContentLoad.Init"> 
        ................................................... 
        </SfTab> 
    </div> 
</div> 
  
UnitTest1.cs::    
using Bunit; 
using System; 
using Xunit; 
using Xunit; 
using SFTabsDemoTest; 
using SFTabsDemo.Pages; 
using Syncfusion.Blazor; 
using System.Threading.Tasks; 
  
namespace SFTabsDemoTest 
{ 
    public class UnitTest1 : TestContext 
    { 
        public void Setup() 
        { 
            Services.AddSyncfusionBlazor(options => { 
                options.IgnoreScriptIsolation = true; 
            }); 
        } 
  
            [Fact] 
        public async Task IsPopulate() 
        { 
            Setup(); 
            var renderedComponent= RenderComponent<SFTabsDemo.Pages.Index>(); 
            await Task.Delay(1000); 
            //renderedComponent.MarkupMatches("Tab1"); 
            Assert.Equal("Tab1", renderedComponent.Find("." + "e-toolbar-item").TextContent); 
            Assert.Equal("Tab2", renderedComponent.FindAll("." + "e-toolbar-item")[1].TextContent); 
            Assert.Equal("Tab3", renderedComponent.FindAll("." + "e-toolbar-item")[2].TextContent); 
            Assert.Contains("Hey, I should be generated", renderedComponent.Markup); 
            Assert.Contains("Weather forecast", renderedComponent.Markup); 
            Assert.Contains("Survey Prompt", renderedComponent.Markup); 
            //line 27 shows an error that "text is missing" because tab1 and tab2 is not rendered 
        } 
        
    } 
} 
  
 
  
 
  
Kindly try the above project and let us know if this meets your requirement. 
  
Also the unit tests for buttons do not work for onclick event. 
  
We have forwarded this problem to the concern team and get back to you by 27th Jan 2022.  
  
Regards, 
Satheesh Kumar B 



SK Satheesh Kumar Balasubramanian Syncfusion Team January 28, 2022 04:11 PM UTC

Hi Abhishek, 
  
Also the unit tests for buttons do not work for onclick event. 


 
Please find the below code snippet for button unit testing, 
  
[Fact(DisplayName = "On Clicked")] 
        public async Task OnClick() 
        { 
            Setup(); 
            var cut = RenderComponent<SFTabsDemo.Pages.Index>(); 
            await Task.Delay(1000); 
            var btnElems = cut.FindAll("button", true); 
            // click 
            btnElems[0].Click(); 
            var btnContent = btnElems[0].TextContent.Trim(); 
            Assert.Equal("Click me", btnContent); 
        } 
  
Please find the sample link, 
  


 
Regards, 
Satheesh Kumar B 


Loader.
Up arrow icon