React 测试库覆盖延迟加载

ank*_*pta 11 reactjs jestjs redux-mock-store react-testing-library react-hooks

如何覆盖react测试库中的延迟加载组件。

import React, {lazy} from 'react';
const ownerInfo = lazy(() => import('../abc'))

const compone = () => {
  return <Suspense><abc /></Suspense>
}
export default compone
Run Code Online (Sandbox Code Playgroud)

测试规范.js

 import React from 'react'
 import {render, fireEvent} from '@testing-library/react'
 import configureStore from 'redux-mock-store'

 ...
Run Code Online (Sandbox Code Playgroud)

ank*_*pta 17

看完视频后,我能够弄清楚如何覆盖延迟负载。假设您有延迟加载组件。

LazyLoad.jsx:

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
Run Code Online (Sandbox Code Playgroud)

LazyComponent.jsx:

import React from 'react'
export default () => <div>I am lazy ! </div>
Run Code Online (Sandbox Code Playgroud)

LazyLoad.spec.jsx:

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())
})
Run Code Online (Sandbox Code Playgroud)

  • 使用“findBy”查询也可以是一种选择吗? (6认同)

Any*_*vas 7

根据React 测试库创建者Kent Dodds 的说法,你应该更喜欢使用而不是findByTextwaitFor + expect.

这两段代码基本上是等效的(find* 查询在底层使用 waitFor),但第二段代码更简单,并且您收到的错误消息会更好。

考虑到这一点,我建议像这样重构你的测试

import React from 'react';
import { render, screen, waitFor } from 'react-testing-library';
import LazyLoad from 'LazyLoad';

test('renders lazy component', async () => {
  const { getByText } = render(<LazyLoad />);
  expect(await screen.findByText('I am lazy !')).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)