using Bunit; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared; namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; /// Retiring an editor during deferred creation cancels its JavaScript registration. [Trait("Category", "Unit")] public sealed class MonacoCreationLifetimeTests : BunitContext { [Fact] public async Task DisposalDuringCreationCancelsTheAttemptAndDoesNotSynchronizeLaterOptions() { Services.AddLogging(); var create = JSInterop.SetupVoid("MonacoBlazor.createEditor", _ => true); JSInterop.SetupVoid("MonacoBlazor.dispose", _ => true).SetVoidResult(); var cut = Render(p => p.Add(x => x.AriaLabel, "Retiring source")); var creation = Assert.Single(JSInterop.Invocations["MonacoBlazor.createEditor"]); cut.Render(p => p.Add(x => x.ReadOnly, true).Add(x => x.AriaLabel, "Retired source")); await cut.InvokeAsync(() => cut.Instance.DisposeAsync().AsTask()); var cancellation = Assert.Single(JSInterop.Invocations["MonacoBlazor.dispose"]); cancellation.Arguments[0].ShouldBe(creation.Arguments[0]); create.SetVoidResult(); await cut.Instance.InitialRenderFinished.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken); // A retired editor must remain uninitialized after the actual creation continuation finished. var read = await cut.InvokeAsync(() => cut.Instance.GetValueAsync()); read.Ok.ShouldBeTrue(); JSInterop.Invocations["MonacoBlazor.setEditorOption"].ShouldBeEmpty(); JSInterop.Invocations["MonacoBlazor.getValue"].ShouldBeEmpty(); } private sealed class RecordedEditor : MonacoEditor { public TaskCompletionSource InitialRenderFinished { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); protected override async Task OnAfterRenderAsync(bool firstRender) { try { await base.OnAfterRenderAsync(firstRender); } finally { if (firstRender) InitialRenderFinished.TrySetResult(); } } } }