-
-
Notifications
You must be signed in to change notification settings - Fork 109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Components render too many times with SetParametersAndRender #1119
Comments
Hi @Jcparkyn, Thanks for reaching out. We have tried to stabilize bUnit the last few months related to blocking the renderer when triggering asynchronous renders. A side effect of that may be what you are observing here. I will try to replicate and see what options we have. |
@linkdotnet this is a case we should also support in V2 code path. |
By any chance can you elaborate how you counted the render cycles in the WebAssemblyRenderer? |
I counted the render cycles by using the Console.WriteLine inside the render function (and by counting how many times a breakpoint in the render function was hit). In my case, one line was written to the console each time the component parameter changed. Here's a minimal repro which can be pasted into the "Empty Blazor Webassembly" template: RenderCountDemo.razor: @{
Console.WriteLine("Rendering RenderCountDemo");
}
X: @X
@code {
[Parameter]
public int X { get; set; }
protected override void OnParametersSet()
{
base.OnParametersSet();
StateHasChanged();
StateHasChanged();
StateHasChanged();
}
} Index.razor: @page "/"
<button @onclick="() => count++">Click me</button>
<RenderCountDemo X="count" />
@code {
int count = 0;
} I should also mention that the problem occurs in BUnit 1.12.6 as well (that's what I was originally using), so I don't think it was a recent regression. |
I've tried this locally, and I am not sure what our options are, if any. My test looked like this: public class MultipleStateHasChangedInOnParametersSet : ComponentBase
{
protected override void OnParametersSet()
{
base.OnParametersSet();
StateHasChanged();
StateHasChanged();
StateHasChanged();
}
}
[Fact]
public void Multiple_calls_to_StateHasChanged_from_OnParametersSet()
{
var cut = RenderComponent<MultipleStateHasChangedInOnParametersSet>();
cut.RenderCount.ShouldBe(1);
cut.SetParametersAndRender();
cut.RenderCount.ShouldBe(2); // fails, cut.RenderCount == 5.
} Some notes:
Interestingly, if we trigger an update to parameters in the following way: @* TriggerChildContentRerenderViaClick.razor *@
<button @onclick="() => counter++">Count = @counter</button>
<MultipleStateHasChangedInOnParametersSet Value="counter" />
@code {
int counter;
} public class MultipleStateHasChangedInOnParametersSet : ComponentBase
{
[Parameter]
public int Value { get; set; }
protected override void OnParametersSet()
{
base.OnParametersSet();
StateHasChanged();
StateHasChanged();
StateHasChanged();
}
}
[Fact]
public void Multiple_calls_to_StateHasChanged_from_OnParametersSet_with_event_dispatch_render_trigger()
{
var cut = RenderComponent<TriggerChildContentRerenderViaClick>();
var child = cut.FindComponent<MultipleStateHasChangedInOnParametersSet>();
child.RenderCount.ShouldBe(1);
cut.Find("button").Click();
child.RenderCount.ShouldBe(2); // this assertion passes
} The expected number of renders does occur. So, I think we need to investigate if we can change our |
Pushed a branch with my (failing tests) for this issue to https://github.com/bUnit-dev/bUnit/tree/bug/1119-Components-render-too-many-times-with-SetParametersAndRender if somebody wants to take a look. Otherwise, I will see what I can do later during the summer. |
Thanks @egil, I think I'll be able to get by with your workaround (or something similar) for now. I'll update this thread if I find anything useful. Here's another workaround that seems to work: @* RenderCountWrapper.razor *@
@ChildContent
@code {
[Parameter] public RenderFragment? ChildContent { get; set; }
} [Fact]
public void Should_have_correct_RenderCount() // passes
{
var x = 10;
var cut = Render<RenderCountWrapper>(@<RenderCountWrapper><RenderCountDemo X="x" /></RenderCountWrapper>);
var component = cut.FindComponent<RenderCountDemo>();
component.MarkupMatches("X=10");
x = 20;
cut.Render();
component.RenderCount.Should().Be(2);
component.MarkupMatches("X=20");
} |
Interesting - will have a look in the upcoming days. |
Okay - here the reason for the different behavior between an initial render and a re-render. if (!_isBatchInProgress)
{
ProcessPendingRender();
} In In the second case (i.e. var result = renderedComponent.InvokeAsync(() =>
renderedComponent.Instance.SetParametersAsync(parameters)); This bypasses |
That's what I thought, @linkdotnet. Do you see a way we can get around that? Using reflection to flip the |
Well I still have to think a bit longer about that, but here is my current view: <p>Hello world!</p>
@{
Console.WriteLine("Rendering RenderCountDemo");
}
@code {
[Parameter]
public int X { get; set; }
protected override void OnParametersSet()
{
base.OnParametersSet();
StateHasChanged();
StateHasChanged();
StateHasChanged();
}
} This component gets updated by the parents That brings me to the point of whether or not this should be "fixed". In a normal Blazor application, you don't have a way to just retrigger the |
@egil, the more I think about that, the less I am inclined to say we should change the behavior. I am more in favor to restrict when one would call |
@linkdotnet I'm not too familiar with the internals, but shouldn't there ideally still be some straightforward way to update the parameters of a CUT, that represents what would happen in a real app? Making a separate parent component per test is doable, but still a lot more work than having an interface like Whether it's worth the time to implement is another question, of course. |
Fair point - my argument goes in the direction that the render count is an internal thing. As such, it can vary depending on what you are doing. To your original request, what you observed in the browser and what you are doing in the test - they are just different things. And yes it is a bit unfortunate that it isn't visible to you. Functions like |
I do not disagree. That said, I think it would be nice if we can emulate what happens when a parent component passes new parameters to a child component via the |
Yeah we could do that - probably, we have to investigate a bit deeper on what is going on here. I do feel not very comfortable setting a private flag via Reflection (but I don't see any alternative at the moment). A bit off-topic but somewhat related I found some interesting bits in the Blazor code: // Note: We should be careful to ensure that the framework never calls
// IComponent.SetParametersAsync directly elsewhere. We should only call it
// via ComponentState.SetDirectParameters (or NotifyCascadingValueChanged below).
// If we bypass this, the component won't receive the cascading parameters nor
// will it update its snapshot of direct parameters. |
Neat find. I'll play a little with reflection tonight and see what's possible. For V2 and .net 8 the ComponentState has been - made public so we may have a less hacky way to the goal line |
Nice - looking forward to what you are coming up. For |
The first attempt with just getting var result = renderedComponent.InvokeAsync(() =>
{
var renderer = renderedComponent.Services.GetService<ITestRenderer>();
var componentState = typeof(Renderer).GetMethod("GetRequiredComponentState", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(renderer, new object[] { renderedComponent.ComponentId });
var setDirectParametersMethod = componentState.GetType().GetMethod("SetDirectParameters", BindingFlags.Public | BindingFlags.Instance);
setDirectParametersMethod.Invoke(componentState, new object[] { parameters });
}); This still triggers 5 render cycles. |
Yeah because those functions don't set the |
Got it working. Only a POC, but this may be a path forward: d7a0a2a I am not too afraid of using reflection for the older versions of Blazor, they are unlikely to change. For .NET 8 we may ping the team and ask if they can expose the functionality. I am essentially doing:
|
Nice one. I'd argue that the majority of that code should live inside the |
Somewhat related: dotnet/aspnetcore#48980 |
Hi @Jcparkyn, ill push a preview version of bunit out in a little while that you can try out. That should solve this issue. If not, please let us know. |
Thanks @egil, I tried out the latest preview and it's working perfectly, including on my real tests. |
In certain cases, calls to StateHasChanged behave differently in BUnit than in regular Blazor WASM (I haven't tested server-side, but I'd expect it to have the same problem). This means that components in BUnit render too many times, and
RenderCount
values in BUnit are often higher than they should actually be. I have observed this when using SetParametersAndRender, but I'm not sure if there are other scenarios where this happens.This is a problem in my case, because I care a lot about the number of renders, but I have no way to reliably assert the RenderCount in tests.
Example:
Testing this component:
With this test:
Results in this output:
Expected behavior:
The test passes. Using the same component in a Blazor WASM app results in one render each time the parameter changes, but in BUnit I get three (edit: four). This is not just a problem with the "RenderCount" property, the actual render method is being called four times as well (confirmed with a breakpoint).
Version info:
Additional context:
I am obviously not calling
StateHasChanged()
multiple times in succession like the example above, but there are lots of dependencies etc. which can result in redundant calls to StateHasChanged. In a normal Blazor app, the calls would get "batched" into a single render, so long as they occur synchronously.The text was updated successfully, but these errors were encountered: