在比較快照之前,我正在嘗試使用@testing-library/react waitfor等待延遲加載的組件。
App.tsx 就是這樣:
const MyComponent = lazy(() => import('my/component'));
function App() {
return (
<Suspense
fallback={
<div>
<h1>Loading…</h1>
</div>
}
>
<MyComponent />
</Suspense>
);
MyComponent是:
export const MyComponent = memo(() => {
return <div data-testid='test' />;
});
測驗是:
describe('<App />', () => {
it('should render the App', async () => {
const { container, findByTestId } = render(<App />);
await waitFor(() => findByTestId('test'));
expect(container.firstChild).toMatchSnapshot();
});
});
waitFor超時是因為沒有findByTestId('test')找到組件。如果我替換<MyComponent />為<div data-testid='test' />然后測驗按預期作業。
如果延遲加載,為什么不能正確渲染?
亞當
uj5u.com熱心網友回復:
來自React.lazy檔案:
React.lazy接受一個必須呼叫動態的函式import()。這必須回傳一個Promise決議為具有default包含 React 組件的匯出的模塊的模塊。
這是該React.lazy方法的簽名:
function lazy<T extends ComponentType<any>>(
factory: () => Promise<{ default: T }>
): LazyExoticComponent<T>;
所以factory函式應該是:
const MyComponent = lazy(() => import('./component').then(({ MyComponent }) => ({ default: MyComponent })));
此外,您不需要waitFor與查詢一起使用findBy*,因為:
findBy*方法是getBy*查詢和waitFor
完整的作業示例:
component.tsx:
import React from 'react';
import { memo } from 'react';
export const MyComponent = memo(() => {
return <div data-testid="test" />;
});
index.tsx:
import React, { lazy, Suspense } from 'react';
const MyComponent = lazy(() => import('./component').then(({ MyComponent }) => ({ default: MyComponent })));
export function App() {
return (
<Suspense
fallback={
<div>
<h1>Loading…</h1>
</div>
}
>
<MyComponent />
</Suspense>
);
}
index.test.tsx:
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { App } from '.';
describe('<App />', () => {
it('should render the App', async () => {
const { container, findByTestId } = render(<App />);
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
<h1>
Loading…
</h1>
</div>
`);
const mycomp = await findByTestId('test');
expect(mycomp).toBeInTheDocument();
expect(container.firstChild).toMatchInlineSnapshot(`
<div
data-testid="test"
/>
`);
});
});
測驗結果:
PASS stackoverflow/71926928/index.test.tsx (11.382 s)
<App />
? should render the App (78 ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
component.tsx | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 2 passed, 2 total
Time: 12.685 s
包版本:
"react": "^16.14.0",
"jest": "^26.6.3",
"@testing-library/react": "^11.2.7"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460045.html
