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

the*_*uls 5 javascript reactjs jestjs react-testing-library

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

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

我想测试一下,当事实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()
  });
Run Code Online (Sandbox Code Playgroud)

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

TestingLibraryElementError:无法通过以下方式找到元素:[data-testid =“my-component”]

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

sli*_*wp2 7

来自文档查询类型

\n
\n

getBy...:返回查询的匹配节点,如果没有元素匹配或找到多个匹配项,则抛出描述性错误(如果需要多个元素,请使用 getAllBy 代替)。

\n
\n
\n

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

\n
\n

你应该使用queryByTestId()方法。

\n

例如

\n

index.tsx

\n
import React from \'react\';\n\nexport const MyComponent = ({ renderNothing }) => {\n  if (renderNothing) {\n    return null;\n  }\n  return <div data-testid="my-component">Stuff</div>;\n};\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.tsx

\n
import { render, screen } from \'@testing-library/react\';\nimport \'@testing-library/jest-dom/extend-expect\';\nimport React from \'react\';\nimport { MyComponent } from \'./\';\n\ndescribe(\'68258524\', () => {\n  it(\'should pass\', () => {\n    render(<MyComponent renderNothing={true} />);\n    const myComponent = screen.queryByTestId(\'my-component\');\n    expect(myComponent).not.toBeInTheDocument();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

测试结果:

\n
 PASS  examples/68258524/index.test.tsx (10.749 s)\n  68258524\n    \xe2\x9c\x93 should pass (23 ms)\n\n-----------|---------|----------|---------|---------|-------------------\nFile       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n-----------|---------|----------|---------|---------|-------------------\nAll files  |   83.33 |       50 |     100 |      80 |                   \n index.tsx |   83.33 |       50 |     100 |      80 | 7                 \n-----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        12.256 s\n
Run Code Online (Sandbox Code Playgroud)\n