Skip to content

Instantly share code, notes, and snippets.

@itaditya
Created February 14, 2022 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itaditya/4b751140ee8ba335f24c0c41eafdf18e to your computer and use it in GitHub Desktop.
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.
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