How can I test the dialog Close event using bUnit?

If I have an SfDialog and have some DialogEvents

    [Parameter]

    public EventCallback<SaveOrCancelEventArgs> OnChange { get; set; }

    <DialogEvents OnClose="@CloseDialog"></DialogEvents>


    private async Task CloseDialog()

    {

        await OnChange.InvokeAsync(new SaveOrCancelEventArgs { Save = saveOnExit, CloseDialog = true });

    }

How can i test these methods in my bUnit test?

I have tried doing the following test but my onClickHandler is never called:


        Action<SaveOrCancelEventArgs> onClickHandler = _ =>

        {

            //inspect args here?

        };


        var cut = TestContext.RenderComponent<EditDialog>(parameters => parameters

                .Add(s => s.OnChange, onClickHandler)

                .Add(s => s.Visible, true)

                );


        var dialog = cut.FindComponent<SfDialog>();


        await dialog.Instance.CloseDialog(null);


When I debug the test I see that the CloseDialog method is not invoked during the test run (although it works fine if the application is running in the browser.

What do I need to do to test behaviour triggered by a dialog





3 Replies 1 reply marked as answer

BS Buvana Sathasivam Syncfusion Team February 22, 2022 07:50 PM UTC

Hi Kaine, 

Greetings from Syncfusion support. 

You can call the SfDialog HideAsync public method to trigger the OnClose event. The OnClose event is triggered before the SfDialog is closed. Can you find the below code for your reference? 

[Fact(DisplayName = "Events testing")] 
        public async Task Events() 
        { 
            var onCloseCount = 0; 
            var dialog = RenderComponent<SfDialog>(options => options.Add(p => p.IsModal, true).AddChildContent<DialogEvents>(events =>  
                events.Add(e => e.OnClose, () => { // SfDialog OnClose event 
                    onCloseCount++; 
                    Assert.NotNull("OnClose event is triggered"); 
                    Assert.Equal(1, onCloseCount); 
                }))); 
            var rootEle = dialog.Find(".e-dialog"); 
            await dialog.Instance.ShowAsync(); 
            await dialog.Instance.HideAsync(); // Hide the dialog to trigger the close event 
        } 
 

Please let us know if you have any concerns. 

Regards, 
Buvana S 


Marked as answer

KA Kaine February 23, 2022 05:21 PM UTC

Great, thanks.


As a note to anyone else that might be trying to do this, if the dialog is a child component of the Component Under Test then you need to do:


        var dialog = cut.FindComponent<SfDialog>();

        await dialog.InvokeAsync(() => dialog.Instance.ShowAsync());

        await dialog.InvokeAsync(() => dialog.Instance.HideAsync());


othrwise you get a thread sync exception



BS Buvana Sathasivam Syncfusion Team February 24, 2022 01:01 PM UTC

Hi Kaine, 

Most welcome. Please let us know if you have any other concerns. 

Regards, 
Buvana S 


Loader.
Up arrow icon