测试反应加载组件
Testing react-loadable components
我在测试使用 react-loadable
的 React
组件时遇到问题。说,我有一个 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>
)
}
然而,当我测试这个组件时,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
s 的优雅方法来处理这种情况?
我没有使用 react-loadable 的个人经验,但我实现了一个类似的组件,它通过动态 import()
语法处理代码拆分。
为了让 Jest 与 'loadable' / 'async' 组件一起工作,我必须为 Jest 配置 .babel-rc
配置以包含 dynamic-import-node babel 插件即使导入是异步的,也可以正确解析模块。
所以,答案是阅读文档 - 自我提醒!基于 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
一起使用。
我在测试使用 react-loadable
的 React
组件时遇到问题。说,我有一个 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>
)
}
然而,当我测试这个组件时,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
s 的优雅方法来处理这种情况?
我没有使用 react-loadable 的个人经验,但我实现了一个类似的组件,它通过动态 import()
语法处理代码拆分。
为了让 Jest 与 'loadable' / 'async' 组件一起工作,我必须为 Jest 配置 .babel-rc
配置以包含 dynamic-import-node babel 插件即使导入是异步的,也可以正确解析模块。
所以,答案是阅读文档 - 自我提醒!基于 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
一起使用。