|
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);
|
|
[TestMethod]
public async Task SyncfusionGrid()
{
MockJsRuntimeInvokeHandler JSRuntimeMock = null;
// Arrange
using var ctx = new Tests();
ctx.Services.AddScoped<NavigationManager, MockNavigationManager>();
ctx.Services.AddSyncfusionBlazor();
// Act
JSRuntimeMock = ctx.Services.AddMockJsRuntime();
if (JSRuntimeMock != null)
{
JSRuntimeMock.Setup<bool>("sfBlazor.isRendered", new { }).SetResult(true);
}
List <BusinessObject> callResult = new List<BusinessObject>()
{
new BusinessObject{ TaskName = "Andrea" },
new BusinessObject { TaskName = "Mario" }
};
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonSerializer.Serialize(new UrlResult<BusinessObject>() { Result = callResult, Count = callResult.Count }))
};
var cut = ctx.RenderComponent<SyncfusionGrid>();
await Task.Delay(2000);
// Assert
var count = cut.FindAll(".e-row").Count;
Assert.IsTrue(2 == count, "Number of rows not generated properly");
}
[ServerSide.Data] |
@Vignesh Natarajan
Is something similar available for ASP.net core MVC syncfusion. I cannot find any examples for the same.
Hi Support!
I have a similar issue and I'm trying the above solution, but it is not working for me.
I put breakpoints on DataBound and ActionFailure events on my grid but none of them is being called.
Also I tried to use MockHttpMessageHandler's GetMatchCount method, but it always returns zero. It seems to me Grid's DataManager HttpClient is not being called at all, as no rows are being appended to my grid.
My setup is very similar to the above, except that I send additional parameters to the server by using a Query instance.
This Query is populated in OnInitializedAsync method.
Please let me know if you require further details.
Any help is highly appreciated.
Best regards,
Marco.
Hi Marco,
Query : I put breakpoints on DataBound and ActionFailure events on my grid but none of them is being called. It seems to me Grid's DataManager HttpClient is not being called at all, as no rows are being appended to my grid.
We are not clear about the exact scenario you are facing the reported problem. We suggest you to ensure to have defined the SfDataManager as like our below documentation to bind remote data to Grid.
https://blazor.syncfusion.com/documentation/datagrid/data-binding#remote-data
If you are still facing difficulties then, we need the following details to further procced on this scenario,
The provided information will help us analyze the problem, and provide you a solution as early as possible.
Regards,
Renjith R
Hi Renjith,
Sorry for the late reply.
Please find below details about my Grid, Adaptor and the Service:
<SfGrid @ref="_grid" TValue="Response" ID="Grid" Query="@_gridQuery"
Height="100%" AllowPaging="true" AllowSorting="true" Toolbar="@(new [] { "Search" })">
<SfDataManager Adaptor="Adaptors.CustomAdaptor" EnableCaching="true">
<CustomWebApiAdaptor />
</SfDataManager>
<GridEvents TValue="Response" DataBound="OnGridDataBound" OnActionBegin="OnGridActionBegin"
OnActionFailure="OnGridActionFailure" RowSelected="OnGridRowSelectedAsync" />
... (Sort, Search and paging settings -- omitted for brevity)
<GridColumns>
<GridColumn Field=@nameof(Response.Id) HeaderText="Id" IsIdentity="true" AllowSearching="false" Visible="false" />
<GridColumn Field=@nameof(Response.Name) HeaderText="Nome" Width="120" />
<GridColumn Field=@nameof(Response.FullAddress) HeaderText="Endereço" HideAtMedia="(min-width: 600px)" Width="300" />
</GridColumns>
</SfGrid>
public class CustomWebApiAdaptor : DataAdaptor<DataService>
{
public override async Task<object> ReadAsync(DataManagerRequest dm, string? key = null)
{
ArgumentNullException.ThrowIfNull(dm, nameof(dm));
var dataSource = await Service.ListAsync(new GetDataList { QueryOptions = dm.ToODataOptions() });
if (dataSource is null)
{
throw new InvalidOperationException("Retorno da API não pode ser nulo.");
}
return dm.RequiresCounts
? new DataResult() { Result = dataSource.Items, Count = dataSource.Count }
: dataSource.Items;
}
}
public class DataService
{
private readonly HttpClient _httpClient;
public DataService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public virtual async Task<ApiListResponse<Response>?> ListAsync(GetDataList request)
{
var url = $"Data?{request.QueryOptions}";
var result = await _httpClient.GetAsync(url);
result.EnsureSuccessStatusCode();
string responseBody = await result.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<ApiListResponse<Response>>(responseBody, GetJsonSerializerOptions());
}
private static JsonSerializerOptions GetJsonSerializerOptions()
{
...
}
}
Here is my test case:
[Theory, AutoData]
public async void ShouldRenderComponentPopulatingGrid(Guid id1, Guid id2)
{
MockHttpMessageHandler mock = Services.AddMockHttpClient();
var callResult = new List<Response>()
{
new() { Id = id1, Name = "Item 1" },
new() { Id = id2, Name = "Item 2" }
};
HttpResponseMessage respMsg = new(HttpStatusCode.OK)
{
Content = JsonContent.Create(JsonSerializer.Serialize(new { Result = callResult, Count = callResult.Count }))
};
var request = mock.When("Data*").Respond(req => respMsg);
var cut = Render(@<GridComponent />);
var sfGrid = cut.FindComponent<SfGrid<Response>>();
var matches = mock.GetMatchCount(request); // Always returns zero
}
Any help is appreciated.
Best regards,
Marco.
Hi Marco,
Thanks for the update.
We are currently checking the reported query from our end and we will update the further details within two business days. Until then we appreciate your patience.
Regards,
Rahul
Hi Marco,
We suspect that there might be some problem with your way of rendering CustomAdaptor as component which might have caused the reported problem. So ,we suggest you to refer to the below documentations for more details on rendering CustomAdaptor as component.
https://blazor.syncfusion.com/documentation/datagrid/custom-binding#custom-adaptor-as-component
We have also prepared a sample by rendering CustomAdaptor as component and fetching data from service to bind in Grid. Please download and refer the sample from the link below,
Sample : https://www.syncfusion.com/downloads/support/directtrac/general/ze/ServerApp-826918869
Please refer the above sample and reference documentation and check this from your side. If you are still facing difficulties, then kindly get back to us with an issue reproducing sample based on your scenario for us to proceed further.
Regards,
Renjith R
Hi Renjith ,
Thanks for the reply.
However, by taking a thorough look at the sample provided in this reply I managed to find the issues.
1) I did not add the DataService to my service providers collection in my test case (duh...)
2) The BaseUri of my mocked HttpClient was not matching the BaseUri in my tests (duh again...)
Fixing the two items above, it seems to be working fine.
Nevertheless, I was intrigued by the following piece of code in the sample:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
CustomersIpinsTreeGrid.Refresh();
}
}
This refresh is not really necessary when the application is executed, and, even the unit test works fine when I comment it, EXCEPT if I have a column with the HideAtMedia clause configured. In these cases, the test only works if the refresh is performed after rendering.
Is this expected behavior?
Best regards,
Marco.
Hi Marco,
Thanks for the update.
Query: “In these cases, the test only works if the refresh is performed after rendering. Is this expected behavior?”
Yes, because some complex properties of GridColumn require some additional refresh to run the Unit test case without error. We have ensured the GridComponent with different combinations, and we have faced some issues with test cases. Hence we added an additional refresh in the OnAfterRenderedAsync to succeed in the test case.
Please
get back to us if you have further queries or if you are facing issues with it.
Regards,
Vignesh Natarajan