检查组件是否未呈现的最佳实践

Ant*_*kis 8 javascript testing unit-testing reactjs react-testing-library

让我们假设一个组件在 render 方法中返回 null,基于一些 prop。

使用 expect 来确保不呈现组件的最佳方法是什么?

例子:

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Pagination from '../Pagination';

it('should not render if totaPages is 0', () => {
  const { container } = render(<Pagination activePage={1} totalPages={0} />);
  expect(container.firstChild).toBeNull();
});
Run Code Online (Sandbox Code Playgroud)

上面的代码够吗?

Gio*_*Gpx 8

如果你使用jest-dom你可以做expect(container).toBeEmptyDOMElement(). 我发现它更具可读性,但您的解决方案也有效