Skip to content

Instantly share code, notes, and snippets.

@pattiereaves
Last active August 13, 2020 17:08
Show Gist options
  • Save pattiereaves/b263417121dccaafab7b28b1451b5362 to your computer and use it in GitHub Desktop.
Save pattiereaves/b263417121dccaafab7b28b1451b5362 to your computer and use it in GitHub Desktop.
React Testing Library example

React Testing Library example

These files are an example of how you could do TDD using React Testing Library. To recreate

  • Add files to a project (I spun up a create react app project)
  • Go through the steps to install React Testing Library
  • Run the test task through the debug script on your package.json. This opens up a debug instance so that you can stop on breakpoints within the component or the test in order to check values.

Mucho props to Christina for her super helpful RFC comparing react testing library vs enzyme. I found her pull request to set up these tests in Irving to be a very useful reference setting them up in my own project.

COP-123 Make a button to toggle more information

User story

As a user, I want to be able to see more information by clicking on a button.

Acceptance criteria

  • The information is hidden when the page loads.
  • When the user clicks a button, they can see more information.
  • When the user clicks the a second time, the information is hidden.
import React, { useState } from 'react';
export default ({ info }) => {
const [isVisible, setIsVisible] = useState(false);
return (
<>
<button aria-controls="info" onClick={() => setIsVisible(!isVisible)}>Show info</button>
{isVisible && <p id="info" role="dialog">{info}</p>}
</>
);
}
import React from 'react';
import {
render, screen, fireEvent,
} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Button from './Button';
test('The information is hidden when the the component loads.', () => {
render(<Button info="This is my info"/>);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('The information is visible when the button is clicked.', () => {
render(<Button info="This is my info"/>);
fireEvent.click(
screen.getByRole('button')
);
expect(screen.queryByRole('dialog')).toBeVisible();
});
test('The information is hidden when you click on the button a second time.', () => {
render(<Button info="This is my info"/>);
fireEvent.click(
screen.getByRole('button')
);
expect(screen.queryByRole('dialog')).toBeVisible();
fireEvent.click(
screen.getByRole('button')
);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment