How to test placeholder of input using Jest with React Testing Library
Asked Answered
P

3

8

I've built a simple react application with a searchbar component. The searchbar component contains an Input. For testing Im using Jest with React Testing Library. I want to write a test which tests that the input's placeholder disappears when something is typed into the value of that input.

Searchbar.test.tsx

test("SearchBar placeholder gets replaced by search string", () => {
  const handleSearchRequest = jest.fn();
  render(<SearchBar searchInputValue="Hello World"/>);
  
  const searchInput = screen.getByPlaceholderText("Search");

  expect(searchInput).toBeFalsy();                  //test fails
  // expect(searchInput).not.toBeInTheDocument();   //test fails
  // expect(searchInput).toBeNull();                //test fails
});

Searchbar.tsx

      <Input
        placeholder="Search"
        value={currentValue}
      />

Any ideas of how I should write this test?

Parmenter answered 16/2, 2021 at 15:1 Comment(2)
What's the error you get ?Progressionist
There isn't necessarily an error. The test fails because searchInput is truthy which means that screen.getByPlateholderText is finding the component even though the placeholder is not displayed.Parmenter
D
22

To understand what you are testing, by using Jest and React Testing Library you are rendering those components in the JSDOM, and then reading the JSDOM output of that render.

When you have an input with a placeholder,

<input placeholder="this is a placeholder" />

you can query it by

screen.queryByPlaceholderText(/this is a placeholder/i)

But when the input already has a value, after the user has typed in, the output would be:

<input placeholder="this is a placeholder" value="user text" />

And you can still query it by

screen.queryByPlaceholderText(/this is a placeholder/i)

The only way of making the placeholder disappear is to actually remove the placeholder when there is no value, so that there is no placeholder text at that point, and you could test that, in case that test is useful.

Disinterest answered 16/2, 2021 at 19:0 Comment(0)
A
6

If you want to test the placeholder value

expect(inp).toHaveAttribute("placeholder", "test")
Abbyabbye answered 28/12, 2021 at 6:30 Comment(0)
H
4

You can take an element by it's placeholder with:

screen.getByLabelText('Length')

You can take the placehoder of the element like this:

screen.getByLabelText('Length').getAttribute("placeholder")

For example, to test that a placeholder has a certain value you could:

expect(screen.getByLabelText('Length').getAttribute("placeholder")).toBe("e.x. 260 mm");
Huber answered 12/11, 2021 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.