使用 querySelectorAll 而不是 querySelector 来测试 toBeInTheDocument

Using querySelectorAll instead of querySelector for testing with toBeInTheDocument

是否可以将 querySelectorAll 与 jest react 测试一起使用,而不是使用 querySelector 单独选择每个组件并使用 toBeInTheDocument 检查它们是否在文档中?

例如,测试这样一个组件:

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

否则需要编写这样的测试:

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();
  });
});

我有一个包含许多元素的列表,它开始变得很长。

检查 p 元素的编号并使用 for...loop 检查每个元素是否在文档中。所以你不需要一一断言。

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();
    });
  });
});