I have an svg inside a React component that renders conditionally.
<div className='avatar'>
{gender === true ? <MaleAvatar /> : <FemaleAvatar />}
</div>
MaleAvatar and FemaleAvatar are components containing svgs. Initially, I want the MaleAvatar svg to render and then if the value of gender is changed to false the FemaleAvatar svg renders - but the male avatar should render first and that's what I want to test.
The component the conditional is in is a child of a child, but I am testing elements in that component by text and the test works fine eg:
const personDetailsText = screen.getByText('Personal details')
I am testing with jest and react-testing-library, but using a testing id on the parent div then grabbing the first child doesn't work because it can't recognise the testing id. So if I have:
<div data-testid='avatar' className='avatar'>
{gender === true ? <MaleAvatar /> : <FemaleAvatar />}
</div>
...then the test below fails at 'const avatarSVG = screen.getByTestId('avatar')':
test('gender avatar is male on initialisation', () => {
const avatarSVG = screen.getByTestId('avatar')
expect(avatarSVG).toBeInTheDocument()
expect(() => screen.getByTestId('female-avatar').toThrow())
expect(avatar.firstChild.nodeName).toBe('MaleAvatar')
})
I'm using React hooks and I've read I also need to somehow compensate for React rendering the SVGs after the initial render - after useEffect is finished, but I can't find how to do this with react-testing-library and hooks?
This also does not work:
const avatarSVG = document.querySelector('MaleAvatar')
How can I grab the SVG components to check the correct one renders?
data-testid="avatar"
element is rendered async after data loads, then that explains why your syncronousscreen.getByTestId('avatar')
call is failing. Did you tryawait screen.findByTestId('avatar')
? More information seems needed to be able to answer this, i.e. a minimal reproducible example. – Frodina