art*_*ras 5 javascript reactjs react-loadable react-testing-library
我在测试React使用的组件时遇到了麻烦react-loadable。说,我有一个Button组件,取决于它是否接收icon道具,它会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>
)
}
Run Code Online (Sandbox Code Playgroud)
但是,当我测试该组件时,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()
})
})
Run Code Online (Sandbox Code Playgroud)
有没有一种不使用实际setTimeouts 的优雅方法来处理这种情况?
所以,答案是阅读文档 -自我提示!基于文档的解决方案如下:
describe('Button', () => {
it('renders icon correctly', async () => {
const {getByText} = render(
<Button
icon='add'
/>
)
const icon = await waitForElement(() => getByText('add'))
expect(icon).toBeInTheDocument()
})
})
Run Code Online (Sandbox Code Playgroud)
另请注意,async需要与 一起使用await。
| 归档时间: |
|
| 查看次数: |
1206 次 |
| 最近记录: |