Search code examples
reactjstddjestjsreact-testing-libraryreact-test-renderer

React Testing Library: Do I need a new test with new selectors for each test key?


I'm building a React app with TDD using React Testing Library.

TLDR: Selectors (e.g. toBeInTheDocument()) only seem to work once, after render. Is that right?

I made the app using CRA and here is my src/setupTests.js:

// react-testing-library renders your components to document.body,
// this will ensure they're removed after each test.
import "react-testing-library/cleanup-after-each";
// this adds jest-dom's custom assertions
import "jest-dom/extend-expect";

Here are the tests that I wrote:

import { pluck } from "ramda";
import React from "react";
import { render } from "react-testing-library";
import ContactList from "../components/ContactList";
import { contacts } from "../fixtures";

describe("Contact List", () => {
  describe("given no contacts", () => {
    const { getByText } = render(<ContactList />);

    it("displays 'First Name' in the header", () => {
      const actual = getByText(/first name/i);
      expect(actual).toBeInTheDocument();
    });

    it("displays 'Last Name' in the header", () => {
      const actual = getByText(/last name/i);
      expect(actual).toBeInTheDocument();
    });

    it("displays 'No Contacts'", () => {
      const actual = getByText(/no contacts/i);
      expect(actual).toBeInTheDocument();
    });
  });

  describe("given a list of contacts", () => {
    const props = { contacts };

    const { getAllByTestId } = render(<ContactList {...props} />);

    it("displays the first name of all contacts", () => {
      const actual = pluck("textContent")(getAllByTestId("contact-first-name"));
      const expected = pluck("firstName")(contacts);
      expect(actual).toEqual(expected);
    });

    it("displays the last name of all contacts", () => {
      const actual = pluck("textContent")(getAllByTestId("contact-last-name"));
      const expected = pluck("lastName")(contacts);
      expect(actual).toEqual(expected);
    });
  });
});

And here is the component that I wrote:

import React from "react";
import PropTypes from "prop-types";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import withStyles from "@material-ui/core/styles/withStyles";
import strings from "../strings";

function ContactList({ contacts }) {
  const renderContact = ({ firstName = "N/A", lastName = "N/A", id }) => (
    <TableRow key={id}>
      <TableCell data-testid="contact-first-name">{firstName}</TableCell>
      <TableCell data-testid="contact-last-name">{lastName}</TableCell>
    </TableRow>
  );
  return (
    <Table>
      <TableHead>
        <TableRow>
          <TableCell>{strings.firstName}</TableCell>
          <TableCell>{strings.lastName}</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {contacts.length > 0 ? (
          contacts.map(renderContact)
        ) : (
          <TableRow>
            <TableCell>{strings.noContacts}</TableCell>
          </TableRow>
        )}
      </TableBody>
    </Table>
  );
}

ContactList.propTypes = {
  classes: PropTypes.object.isRequired,
  contacts: PropTypes.arrayOf(
    PropTypes.shape({
      firstName: PropTypes.string.isRequired,
      lastName: PropTypes.string.isRequired
    })
  ).isRequired
};

ContactList.defaultProps = {
  contacts: []
};

const styles = {};

export default withStyles(styles)(ContactList);

Now, if I run these test, only the respective first two pass of each describe block.

If for example I give any of the it tests a .only it passes.

What is going on? Am I not able to reuse the same test setup for several assertions? Do I have to call render for each it?


Solution

  • You are importing react-testing-library/cleanup-after-each which removes the rendered components after every test. This is the correct approach however you should render the component in every it block.