如何编写不应在 React 测试库中找到测试 ID 的测试?

How to write a test which should not find a test id in React Testing Library?

有些测试 ID 不应该出现在 DOM 中并且必须对其进行测试。

例如:

describe('MyModal', () => {
  const testIds = [
    'first-test',
    'second-test',
    'third-test'
  ];

  it('should not render MyModal', () => {
    const { getByTestId } = renderWithClientInstance(
      <MyModal open={false} } />
    );
    testIds.forEach((testId) => expect(getByTestId(testId)).not.toBeInTheDocument());
  });
});

但此测试失败并显示以下错误消息:

TestingLibraryElementError: Unable to find an element by: [data-testid="first-test"]

应该如何编写才能检查这些测试 ID 是否不在 DOM 中?

解决方案是使用 queryByTestId 而不是 getByTestId 因为当查询的元素不存在时它不会失败,而是 returns 一个值或 null.

describe('MyModal', () => {
  const testIds = [
    'first-test',
    'second-test',
    'third-test'
  ];

  it('should not queryByTestId MyModal', () => {
    const { queryByTestId } = renderWithClientInstance(
      <MyModal open={false} } />
    );
    testIds.forEach((testId) => expect(queryByTestId(testId)).toBeNull());
  });
});