Gilian
Gilian

Reputation: 1599

React test onchange dom not updating?

I'm trying to test a list filter functionality in react like so:

it("should filter the correct champions", () => {
    const container = document.createElement("div");
    document.body.appendChild(container);

    act(() => {
      render(
        <Router>
          <ChampionList />
        </Router>,
        container
      );
    });

    const championListPre = container.querySelectorAll("tr");

    expect(championListPre.length).toBeGreaterThan(1);

    const search = container.querySelector("input");

    act(() => {
      fireEvent.change(search, { target: { value: "aatrox" } });
    });

    expect(search.value).toBe("aatrox");

    const championListPost = container.querySelectorAll("tr");

    expect(championListPost.length).toBe(1); // This will not be > 1

    unmountComponentAtNode(container);
    container.remove();
  });

However, for some reason react won't rerender the list (my guess) and expect(championListPost.length).toBe(1); will never be true.

The input looks like this:

<input
   className="input"
   type="text"
   placeholder="Champion name"
   value={this.searchValue}
   onInput={this.handleChange}
/>

handleChange changes the state of the component.

I have no clue why this is happening, and I tried different methods, but none worked.

Upvotes: 3

Views: 185

Answers (1)

skyboyer
skyboyer

Reputation: 23705

Your input reacts to onInput but you're triggering onChange. I don't believe there is any kind of magic that translates some event into several close by meaning.

So try

  fireEvent.input(search, { target: { value: "aatrox" } });

Upvotes: 3

Related Questions