Skip to content

Unable to test a non-bound change in the DOM #119

Closed
@unknownterritory

Description

@unknownterritory

I am new to testing-library, so I hope I'm not missing anything obvious.

I have a helper class whose methods make changes in a component's DOM, some upon interaction by the user. I am unable to test those changes with fireEvent or userEvent. It always fails.

I simplified my use case to a very simple example:

  • My svelte component has only a button that modifies the content of a paragraph. The paragraph's content is not bound to a variable intentionally.
  • And then I have a test for it. The test expect(info).toHaveTextContent("Modified by click") fails but, curiously enough, a console.log(paragraph.innerText) shows the change.
  • I also have a codesandbox replicating this example.

Code for the component:

<script>
  // The text content of the paragraph is purposely not bound
  // with any svelte variable. The purpose of this exercise
  // is to reduce to the simplest form my use-case which is
  // to test changes done in html elements of a svelte component
  // by external helper class methods, which do not allow for
  // bindings to exist.
  const modify = () => {
    const par = document.querySelector(".info");
    par.innerText = "Modified by click";
  };
</script>

<div>
  <p class="info" data-testid="info">Click to modify</p>
  <button on:click={modify} label="button">Modify</button>
</div>

The code for the test.

import { render, screen, waitFor } from "@testing-library/svelte";
import "@testing-library/jest-dom/extend-expect";
import userEvent from "@testing-library/user-event";
import Component from "./Component.svelte";

it("should modify the text after clicking the button", async () => {
  render(Component);
  const button = screen.getByRole("button");
  userEvent.click(button);
  const info = screen.getByTestId("info");
  // console.log actually outputs the modified content?
  console.log(info.innerText);
  // The test fails independently of using waitFor or not.
  await waitFor(() => {
    expect(info).toHaveTextContent("Modified by click");
  });
});

Is this a bug of the library or should I be approaching this test differently?

P.S.: I asked on Discord, both in the testing-library and the svelte communities. I've also researched the documentation and previous issues. While I'm not entirely sure this is a bug, I would very much appreciate an indication of where to seek a solution if the fault resides in my approach.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions