我无法测试我的 React
使用 react-loadable
的组件.说,我有一个 Button
组件,取决于它是否收到 icon
Prop ,加载 Icon
像这样的组件:
Button.js
const LoadableIcon = Loadable({
loader: () => import('./Icon'),
loading: () => <div>Loading...</div>
})
function Button(props) {
return (
<button
onClick={props.onClick}>
{props.icon &&
<LoadableIcon name={props.icon} />}
{props.children}
</button>
)
}
然而,当我测试这个组件时,Icon
尚未加载,测试只找到 <div>Loading...</div>
元素...
Button.test.js
import React from 'react'
import {render} from 'react-testing-library'
import Button from '../Button'
describe('Button', () => {
it('renders icon correctly', () => {
const {getByText} = render(
<Button
icon='add'
/>
)
expect(getByText('add')).toBeInTheDocument()
})
})
有没有一种优雅的方法可以在不使用实际 setTimeout
的情况下处理这种情况?是吗?
最佳答案
所以,答案是阅读文档 - self 注意!基于docs的解决方案是以下内容:
describe('Button', () => {
it('renders icon correctly', async () => {
const {getByText} = render(
<Button
icon='add'
/>
)
const icon = await waitForElement(() => getByText('add'))
expect(icon).toBeInTheDocument()
})
})
另外,注意async
需要和await
一起使用。
关于javascript - 测试 react 加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51837887/