'React Testing Library can't find my self-closing tag in a react fragment, and just renders <body/>
I've got a component like this:
const MyComponent = ({ foo }) => (
<>
<div>
<Header />
{foo}
</div>
<div data-testid="self-closing-tag" className={styles.break} />
</>
)
(n.b. React should handle the div being a self-closing tag, whereas without react that's not valid html)
I've written a test that renders my component <div data-testid="foo" /> for the foo prop and runs expect(screen.getByTestId('foo')).toBeInTheDocument(); which passes. If I use screen.debug in that test, I get the fully rendered DOM.
But when I write a test for the self closing tag, like so: expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); I get:
Unable to get element by:
[data-testid="self-closing-tag"]
and where I'd expect it to print out the fully rendered DOM, it just prints <body />.
If I put the expect assertion for the self-closing tag in the test for 'foo', they both pass.
describe('<My Component />', () => {
beforeEach(<MyComponent foo={<div data-testid="foo" />} />);
it('renders foo', () => {
expect(screen.getByTestId('foo')).toBeInTheDocument();
// expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); -- this passes if uncommmented!
};
it('renders the self closing tag', () => {
expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); // cannot find element, prints '<body />' as the DOM.
})
})
I can obviously shove everything in the same it statement, but I'd rather not if possible. I'd also like to understand whats going on.
What have I done wrong?
Solution 1:[1]
That´s because toHaveClass expects an arg with the class name, you can check the docs here.
So, your test could be:
expect(screen.getByTestId("self-closing-tag")).toHaveClass("XX class name you expect XX");
or if you just want to check if the element has the attribute class
expect(screen.getByTestId("self-closing-tag")).toHaveAttribute("class");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luis Paulo Pinto |
