Created
February 14, 2022 16:22
-
-
Save itaditya/4b751140ee8ba335f24c0c41eafdf18e to your computer and use it in GitHub Desktop.
Show that re-querying DOM nodes is necessary in React Testing Library based tests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import { fireEvent, render, screen } from '@testing-library/react'; | |
function clickIncrement() { | |
fireEvent.click( | |
screen.getByRole('button', { | |
name: 'Increment', | |
}), | |
); | |
} | |
function clickToggle() { | |
fireEvent.click( | |
screen.getByRole('button', { | |
name: 'Toggle', | |
}), | |
); | |
} | |
function Comp() { | |
const [count, setCount] = useState(1); | |
const [show, setShow] = useState(true); | |
return ( | |
<div> | |
{show && <h2>{count}</h2>} | |
<button onClick={() => setCount(count + 1)}>Increment</button> | |
<button onClick={() => setShow(!show)}>Toggle</button> | |
</div> | |
); | |
} | |
test('reusing stale DOM nodes can give unexpected results', () => { | |
render(<Comp />); | |
const headingElemInitial = screen.getByRole('heading'); | |
expect(headingElemInitial).toHaveTextContent('1'); | |
clickToggle(); | |
clickIncrement(); | |
clickToggle(); | |
const headingElemFinal = screen.getByRole('heading'); | |
expect(headingElemFinal).toHaveTextContent('2'); | |
expect(headingElemInitial).toHaveTextContent('1'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment