如何使用 React 测试库测试 React 组件是否返回 null 或其子组件?

How to test if React component is returning null or its children using React Testing Library?

我有一个 React 组件 returns 如果 prop isTrue 是 truth-y,它的 children 将由 React 渲染。如果它的 prop isTrue 是 false-y,那么组件 returns null,React 不会渲染任何东西。

我需要将它作为一个组件进行测试,安装它,传递道具,并测试当道具 isTrue 为 truth-y 时它的子项是否被渲染,或者我们得到 null 如果 isTrue 是 false-y.

这是我的组件:

const RenderIf = ({ isTrue, children }) => {
    if (isTrue) {
        return children;
    }
    return null;
}
export default RenderIf

我认为在这种情况下,测试整个 html 可能没问题。 react-testing-library 用一个 div 包装你的内容,所以你可以这样:

const { container } = render(<MyComponent ifTrue={false}>Content</MyComponent>);
expect(container.innerHTML).toBe('<div></div>');

如果您不喜欢这种方法,您仍然可以使用 test-id / text 渲染子项并查询它是否存在。

expect(container).toBeEmptyDOMElement()
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
//...

describe('TestHistory', () => {
  it('should render nothing if there are no history entries', () => {
    // ARRANGE
    // ACT
    const { container } = render(
      <TestHistory version={1} versionHistory={[]} datasetType={DatasetType.VALIDATION} />,
    );

    // ASSERT
    expect(container).toBeEmptyDOMElement();
  });
});