Jest.js 如何在对象内部测试Reac Lazy

5fjcxozz  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(192)

在我正在做的项目中,有一些命名的导出,如下面的对象:

export const object = {
    component: React.lazy(() => import('some-component'))
}

字符串
(They有更多的属性,但为了简洁起见,我只展示这一个)
问题
当我尝试使用Jest测试它时,我无法在React.lazy中进行测试:
x1c 0d1x的数据
我试着嘲笑React.lazy,但没有成功:

jest.mock('react', () => ({
  lazy: () => {
    return 'lazy'
  },
}))

describe('Auth route object', () => {
  it('', () => {
    expect(auth).toBeDefined()
    expect(auth[0].component).toBe('lazy')
  })
})


这返回passed,但它一直在抱怨覆盖率。
我怎么能模拟/测试它呢?
附言:我需要至少90%的覆盖率在这个文件,这就是为什么我不能只是忽略它。

rggaifut

rggaifut1#

您可以使用@testing-library/react来测试React.lazy()方法。此外,如果延迟加载的组件过于复杂,并且您只想测试包含该组件的父组件,则可以使用jest.mock()方法来提供子组件的模拟版本。
例如
index.tsx

import React, { Suspense } from 'react';

export const object = {
  component: React.lazy(() => import('./OtherComponent')),
};

export function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <object.component />
      </Suspense>
    </div>
  );
}

字符串
OtherComponent.tsx

import React from 'react';

export default function OtherComponent() {
  return <div>other component</div>;
}


index.test.tsx

import { MyComponent } from './';
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

function MockedOtherComponent() {
  return <div>mocked other component</div>;
}

jest.mock('./OtherComponent', () => {
  return MockedOtherComponent;
});

describe('67141439', () => {
  it('should pass', async () => {
    render(<MyComponent />);
    const textToMatch = await screen.findByText(/mocked other component/);
    expect(textToMatch).toBeInTheDocument();
  });
});


测试结果:

PASS  examples/67141439/index.test.tsx (10.487 s)
  67141439
    ✓ should pass (40 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.745 s


软件包版本:

"react": "^16.14.0"
"jest": "^26.6.3"
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",

相关问题