javascript - 尝试使用 React 测试库检查不存在的元素总是失败

标签 javascript reactjs jestjs react-testing-library

我有一个组件,在某些情况下应该不呈现任何内容(它只返回 null)。它看起来像这样:

const MyComponent = ({ renderNothing }) => {
    if (renderNothing) {
        return null
    }
    return <div data-testid='my-component'>Stuff</div>
}

我想测试一下,当 renderNothing 为真时,data-testid 为 my-component 的元素不存在。我当前的测试看起来像这样:


  it.only('should not render MyComponent when renderNothing is true ', async () => {
    render(<MyComponent renderNothing={true}/>)
    const myComponent = screen.getByTestId('my-component')
    expect(myComponent).not.toBeInTheDocument()
  });

不幸的是,此测试总是失败并显示以下消息:

TestingLibraryElementError: Unable to find an element by: [data-testid="my-component"]

有没有办法在不触发错误的情况下成功执行此检查?

最佳答案

来自文档 Types of Queries :

getBy...: Returns the matching node for a query, and throws a descriptive error if no elements match or if more than one match is found (use getAllBy instead if more than one element is expected).

queryBy...: Returns the matching node for a query, and returns null if no elements match. This is useful for asserting an element that is not present. Throws an error if more than one match is found (use queryAllBy instead if this is OK).

您应该使用 queryByTestId() 方法。

例如

index.tsx:

import React from 'react';

export const MyComponent = ({ renderNothing }) => {
  if (renderNothing) {
    return null;
  }
  return <div data-testid="my-component">Stuff</div>;
};

index.test.tsx:

import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { MyComponent } from './';

describe('68258524', () => {
  it('should pass', () => {
    render(<MyComponent renderNothing={true} />);
    const myComponent = screen.queryByTestId('my-component');
    expect(myComponent).not.toBeInTheDocument();
  });
});

测试结果:

 PASS  examples/68258524/index.test.tsx (10.749 s)
  68258524
    ✓ should pass (23 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   83.33 |       50 |     100 |      80 |                   
 index.tsx |   83.33 |       50 |     100 |      80 | 7                 
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.256 s

关于javascript - 尝试使用 React 测试库检查不存在的元素总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68258524/

相关文章:

javascript - 从 Angular 将文件添加到 Azure 存储 Blob

javascript - 如何重复空格

jquery - 错误: Path does not match the corresponding path on disk

javascript - 如何不仅将 id 而且将完整对象传递到数组列表中

javascript - 检查数据是否更新

javascript - 错误: Econn is refused in Node.js

javascript - 如果两个组件监听同一数据库引用,我可以选择运行哪个监听器吗?

react-native - Jest : Test suite failed to run (The Expo SDK requires Expo to run)

javascript - 如何使用 Typescript 创建 Jest 自定义环境?

javascript - JQuery 在 Jest 测试中检查元素可见性