2

I want to test whether a modal opens up or not with bunit. The problem is, that the modal doesn't get rendered. How to open a blazored modal with bunit?

Modal Creation in my component under test:

<div style="display: flex; justify-content: flex-end">
    <button class="btn btn-success
                   btn-lg"
                   id="openModalButton"
                  @onclick="CheckOpenModal">
                Hinzufügen
    </button>
</div>
@code 
{
    [CascadingParameter] public IModalService Modal { get; set; }

    private async Task OpenModalForCreation()
    {
        List<string> ParameterA = new List<string>();

        var parameters = new ModalParameters();
        parameters.Add(nameof(CreationModal.ParameterA), ParameterA);

        Modal.Show<CreationModal>("Create something", parameters);
    }
}

My TestClass:

public class PrivateMachinesCompTest : TestContext
{     
    public CompTest()
    {
            Services.AddBlazoredModal();
    }
    [Fact]
    public void CheckOpenModal()
    {
        modalService = new ModalService();
        var cut = RenderComponent<ComponentUnderTest>(parameters => parameters
                .AddCascadingValue(modalService));
        var openModalButton = cut.Find("#openModalButton");
        openModalButton.Click();
        cut.MarkupMatches("Create something");
    }
3r1c
  • 376
  • 5
  • 20

1 Answers1

3

The problem is that you are not rendering the component that actually does the rendering. Just passing in an IModalService doesn't do it.

My approach would be to create a mock of IModalService and assert that the expected method on it is called.

Egil Hansen
  • 15,028
  • 8
  • 37
  • 54
  • It works! I am still wondering if it is possible to render both components and test them together (since it is just a modal) or is this bad practice? – 3r1c Jul 27 '21 at 06:51
  • Its certainly possible to render both in one go. If it is worth it depends on how the model logic is implemented. – Egil Hansen Jul 27 '21 at 17:55
  • If its best practice. It depends, but in this case, I would just have a test that the modal service was invoked and then have a separate test where I render the modal and verify it renders as expected. However, I its a 3rd party modal component, then I want to make sure I dont write tests that tests it, since I will then have to maintain my test when the 3rd model component changes. I like to assume 3rd party stuff I use is tested by its developers :) – Egil Hansen Jul 27 '21 at 17:58