【问题标题】:Attempts to check for element not existing with React Testing Library always failing尝试使用 React 测试库检查不存在的元素总是失败
【发布时间】:2021-07-05 15:19:49
【问题描述】:

我有一个组件在某些情况下不应该渲染(它只返回null)。它看起来像这样:

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

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


  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"]

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

【问题讨论】:

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

来自文档Types of Queries

getBy...:返回查询的匹配节点,如果没有匹配的元素或找到多个匹配项(如果需要多个元素,则使用 getAllBy )。

queryBy...:返回查询的匹配节点,如果没有元素匹配则返回 null。这对于断言不存在的元素很有用。如果找到多个匹配项,则会引发错误(如果可以,则使用 queryAllBy 代替)。

你应该使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    • 2018-07-10
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多