【发布时间】: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"]
有没有办法在不触发错误的情况下成功执行此检查?
【问题讨论】:
-
使用
queryByTestIdtesting-library.com/docs/vue-testing-library/cheatsheet
标签: javascript reactjs jestjs react-testing-library