2023-05-01 18:42:44 +05:30
|
|
|
import {
|
|
|
|
|
render,
|
|
|
|
|
screen,
|
|
|
|
|
waitForElementToBeRemoved,
|
|
|
|
|
} from '@testing-library/react';
|
2023-05-19 13:14:32 +05:30
|
|
|
import React, { ComponentType, Suspense } from 'react';
|
2023-05-01 18:42:44 +05:30
|
|
|
|
|
|
|
|
import Loadable from './index';
|
|
|
|
|
|
|
|
|
|
// Sample component to be loaded lazily
|
|
|
|
|
function SampleComponent(): JSX.Element {
|
|
|
|
|
return <div>Sample Component</div>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const loadSampleComponent = (): Promise<{
|
2023-05-19 13:14:32 +05:30
|
|
|
default: ComponentType;
|
2023-05-01 18:42:44 +05:30
|
|
|
}> =>
|
2023-05-19 13:14:32 +05:30
|
|
|
new Promise<{ default: ComponentType }>((resolve) => {
|
2023-05-01 18:42:44 +05:30
|
|
|
setTimeout(() => {
|
|
|
|
|
resolve({ default: SampleComponent });
|
|
|
|
|
}, 500);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
describe('Loadable', () => {
|
|
|
|
|
it('should render the lazily loaded component', async () => {
|
|
|
|
|
const LoadableSampleComponent = Loadable(loadSampleComponent);
|
|
|
|
|
|
|
|
|
|
const { container } = render(
|
2023-05-19 13:14:32 +05:30
|
|
|
<Suspense fallback={<div>Loading...</div>}>
|
2023-05-01 18:42:44 +05:30
|
|
|
<LoadableSampleComponent />
|
2023-05-19 13:14:32 +05:30
|
|
|
</Suspense>,
|
2023-05-01 18:42:44 +05:30
|
|
|
);
|
|
|
|
|
|
|
|
|
|
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
|
|
|
|
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));
|
|
|
|
|
|
|
|
|
|
expect(container.querySelector('div')).toHaveTextContent('Sample Component');
|
|
|
|
|
});
|
|
|
|
|
|
2023-05-19 13:14:32 +05:30
|
|
|
it('should call lazy with the provided import path', () => {
|
2023-05-01 18:42:44 +05:30
|
|
|
const reactLazySpy = jest.spyOn(React, 'lazy');
|
|
|
|
|
Loadable(loadSampleComponent);
|
|
|
|
|
|
|
|
|
|
expect(reactLazySpy).toHaveBeenCalledTimes(1);
|
|
|
|
|
expect(reactLazySpy).toHaveBeenCalledWith(expect.any(Function));
|
|
|
|
|
|
|
|
|
|
reactLazySpy.mockRestore();
|
|
|
|
|
});
|
|
|
|
|
});
|