Home > Net >  Using querySelectorAll instead of querySelector for testing with toBeInTheDocument
Using querySelectorAll instead of querySelector for testing with toBeInTheDocument

Time:12-23

Is it possible to use querySelectorAll with jest react tests rather than individually selecting each component with querySelector and checking that they're in the document with toBeInTheDocument?

For example, testing a component like this:

const SomeComponent = () => (
  <>
    <p id='one'>one</p>
    <p id='two'>two</p>
    <p id='three'>three</p>
  </>
)

Would otherwise require writing a test like this:

import React from 'react';
import {render} from '@testing-library/react';
import '@testing-library/jest-dom';

describe('Some Component', () => {
  it('Should render all', () => {
    const {container} = render(<SomeComponent/>);

    const one = container.querySelector('#one');
    const two = container.querySelector('#two');
    const three = container.querySelector('#three');

    expect(one).toBeInTheDocument();
    expect(two).toBeInTheDocument();
    expect(three).toBeInTheDocument();
  });
});

I have a list of numerous elements which is starting to get quite lengthy.

CodePudding user response:

Check the number of the p element and use for...loop to check each one of them is in the document or not. So you don't need to assert them one by one.

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { SomeComponent } from '.';

describe('Some Component', () => {
  it('Should render all', () => {
    const { container } = render(<SomeComponent />);
    const matches = container.querySelectorAll('p');
    expect(matches).toHaveLength(3);
    matches.forEach((m) => {
      expect(m).toBeInTheDocument();
    });
  });
});
  • Related