React 测试库覆盖延迟加载
Posted
技术标签:
【中文标题】React 测试库覆盖延迟加载【英文标题】:React testing library to cover the lazy load 【发布时间】:2021-06-14 11:32:06 【问题描述】:如何覆盖 react 测试库中的延迟加载组件。
import React, lazy from 'react';
const ownerInfo = lazy(() => import('../abc'))
const compone = () =>
return <Suspense><abc /></Suspense>
export default compone
test.spec.js
import React from 'react'
import render, fireEvent from '@testing-library/react'
import configureStore from 'redux-mock-store'
...
【问题讨论】:
youtube.com/watch?v=lfb5jvHq9c4 这个有正确的解释如何测试延迟加载组件 感谢@ShubhamVerma 【参考方案1】:观看视频后,我能够弄清楚如何覆盖延迟加载。假设您有延迟加载组件。
Lazyload.js
import React, lazy from 'react'
const LazyComponent = lazy(() => import('./LazyComponent'))
const LazyLoad = () =>
return (
<div>
<div> Lazy component is here: </div>
<React.Suspense fallback=null>
<LazyComponent />
</React.Suspense>
</div>
)
export default LazyLoad
LazyComponent.js
import React from 'react'
export default () => <div>I am lazy ! </div>
lazyLoad.spec.js
import React from 'react'
import render, waitFor from 'react-testing-library'
import LazyLoad from 'LazyLoad'
test('renders lazy component', async () =>
const getByText = render(<LazyLoad />)
await waitFor(() => expect(getByText('I am lazy !' )).toBeInTheDocument())
)
【讨论】:
以上是关于React 测试库覆盖延迟加载的主要内容,如果未能解决你的问题,请参考以下文章
如何使用React.lazy和Suspense进行组件延迟加载
使用 webpack 和 react-router 进行延迟加载和代码拆分不加载