在使用 react-test-library
对异步数据加载的组件进行快照测试时,你需要确保在数据加载完成后再进行快照。以下是一个基本的步骤指南:
@testing-library/react
和 @testing-library/jest-dom
。
npm install --save-dev @testing-library/react @testing-library/jest-domrender
函数渲染组件,并使用 waitFor
或 act
来等待异步操作完成。
import React from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import MyComponent from './MyComponent'; test('renders MyComponent with async data', async () => { render(<MyComponent />); // 等待异步数据加载完成 await waitFor(() => expect(screen.getByText('Expected Data')).toBeInTheDocument()); // 进行快照测试 expect(screen.getByTestId('my-component')).toMatchSnapshot(); });jest.mock
来模拟这些依赖。
import React from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import MyComponent from './MyComponent'; import * as api from './api'; jest.mock('./api'); test('renders MyComponent with async data', async () => { api.fetchData.mockResolvedValue({ data: 'Expected Data' }); render(<My组件 />); // 等待异步数据加载完成 await waitFor(() => expect(screen.getByText('Expected Data')).toBeInTheDocument()); // 进行快照测试 expect(screen.getByTestId('my-component')).toMatchSnapshot(); });import React, { useState, useEffect } from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders MyComponent with async data', async () => {
render(<MyComponent />);
// 等待加载状态消失
await waitFor(() => expect(screen.queryByText('Loading...')).not.toBeInTheDocument());
// 等待数据加载完成
await waitFor(() => expect(screen.getByText('Expected Data')).toBeInTheDocument());
// 进行快照测试
expect(screen.getByTestId('my-component')).toMatchSnapshot();
});
领取专属 10元无门槛券
手把手带您无忧上云