您可以使用@testing-library/react 来测试React.lazy() 方法。另外,如果懒加载组件过于复杂,只想测试包含该组件的父组件,可以使用jest.mock()方法来提供子组件的mocked版本。
例如
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",