Reputation: 1194
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?
Upvotes: 8
Views: 23571
Reputation: 2132
If you want to test the placeholder value
expect(inp).toHaveAttribute("placeholder", "test")
Upvotes: 6
Reputation: 780
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");
Upvotes: 4
Reputation: 1377
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.
Upvotes: 22