S
S
Savelij Tomak2018-11-03 13:47:53
JavaScript
Savelij Tomak, 2018-11-03 13:47:53

How to test behavior of React components (changing state or classes after simulate("event") with Enzyme?

Hello!
I started to delve a little into Enzyme, the question is this: I want to test the behavior in which, after clicking on the button, a new class is added to the input (if it has an empty value). Here is my listing:

it("Search component should mark empty input as invalid after click on button", () => {
    const searchComponent = mount<Search, TSearchProps, ISearchState>(<Search onSearch={{}}/>);
    const searchButton = searchComponent.find(".search__button");
    const searchInput = searchComponent.find(".search__input");

    searchInput.simulate("change", {
      target: {
        value: "",
      },
    });
    searchButton.simulate("click");
    searchComponent.update();

    expect(searchInput.hasClass("search__input_invalid"))
      .toBe(true);
  });

The test fails (although the class is indeed added, although searchComponent.debug() thinks otherwise)
The same question, but with the component state. Here is the resulting listing:
it("Search component should set previous artist name to state in lowercase", () => {
    const searchComponent = mount<Search, TSearchProps, ISearchState>(<Search onSearch={{}}/>);
    const searchInput = searchComponent.find(".search__input");
    const searchButton = searchComponent.find(".search__button");

    const expectedPreviousArtistName = "sting";

    searchInput.simulate("change", {
      target: {
        value: "StiNg",
      },
    });
    searchComponent.update();
    searchButton.simulate("click");
    searchComponent.update();

    expect(searchComponent.state().previousArtistName)
      .toBe(expectedPreviousArtistName);
  });

The test fails, saying that the artist's name is empty.
Thank you all so much for your time!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question