'Test conditional statements reactjs
I want to test this component. When the user searches for something and there is no result, it shows a paragraph with data not found for your search. I think The test by default assumes that this p tag doesn't exist since it is based on a condition.
{searchQuery && data.length === 0 && (
<p data-testid="data-not-found">
data not found for your search
</p>
)}
This is my approach to test this:
it("should show data not found text when user searches and gets no result", async () => {
AxiosInstance.get.mockResolvedValueOnce(mockData)
render(<DataComponent />)
const searchInput = screen.getByTestId("search-input")
const mockQuery = "AQueryThatDoesn'tExistInTheData"
fireEvent.change(searchInput, { target: { value: mockQuery } })
const filteredData = mockData.filter((d) =>
d.name.includes(mockQuery)
)
const dataNotFoundText = screen.queryByTestId("data-not-found")
if (filteredData.length === 0 && searchInput.value === mockQuery) {
expect(dataNotFoundText).toBeInTheDocument()
}
})
I get the following error in the terminal:
expect(received).toBeInTheDocument()
received value must be an HTMLElement or an SVGElement.
Received has value: null
178 |
179 | if (filteredData.length === 0 && searchInput.value === mockQuery) {
> 180 | expect(dataNotFoundText).toBeInTheDocument()
| ^
181 | }
182 | })
183 | })
How can I make this test work properly so when the user finds nothing, it runs this test properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
