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

Best practice to check that a component is not rendered

让我们假设组件 returns 在 render 方法中基于一些属性为 null。

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

上面的代码够用吗?

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