React Testing Library检测元素不存在总是失败如何解决?
问题原因
getByTestId 是 Testing Library 中严格存在性查询的API,当无法匹配到目标元素时,会直接抛出异常,不会执行后续的断言逻辑,因此你还没走到 expect 步骤测试就已经失败了。
解决方案
将查询方法替换为 queryByTestId 即可,该API在匹配不到元素时会返回 null,不会抛出错误,刚好适配元素不存在的校验场景:
it.only('should not render MyComponent when renderNothing is true ', () => { render(<MyComponent renderNothing={true}/>) const myComponent = screen.queryByTestId('my-component') expect(myComponent).not.toBeInTheDocument() });
补充说明
Testing Library 三类基础查询的适用场景:
getBy*:同步查询,找不到直接抛错,仅用于断言元素一定存在的场景queryBy*:同步查询,找不到返回null,仅用于断言元素一定不存在的场景findBy*:异步查询(内部封装了getBy*+waitFor),找不到超时后抛错,用于断言异步渲染的元素最终会存在的场景
如果是需要校验异步消失的元素不存在,可以搭配waitFor使用:
await waitFor(() => { expect(screen.queryByTestId('my-component')).not.toBeInTheDocument() })
内容的提问来源于stack exchange,提问作者theJuls
相关产品推荐
相关产品推荐

