假设我们有一个服务文件 api.js,其中包含一个接口调用函数 fetchData:
// api.js
export const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
};
测试文件
在测试文件中,我们将使用 jest.spyOn 来模拟 fetchData 函数,并返回一个虚拟数据。
// MyComponent.test.jsx
import React from 'react';
import { render, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import MyComponent from './MyComponent';
import * as api from './api';
test('fetches and displays data', async () => {
const mockData = { message: 'Hello, World!' };
// 使用jest.spyOn监视fetchData函数,并模拟返回值
jest.spyOn(api, 'fetchData').mockResolvedValue(mockData);
const { getByText } = render(<MyComponent />);
// 等待数据加载并断言显示内容
await waitFor(() => expect(getByText('Data:')).toBeInTheDocument());
expect(getByText(/Hello, World!/)).toBeInTheDocument();
});
React 组件 MyComponent.jsx,它使用了这个 fetchData 函数:
// MyComponent.jsx
import React, { useEffect, useState } from 'react';
import { fetchData } from './api';
const MyComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const getData = async () => {
const result = await fetchData();
setData(result);
};
getData();
}, []);
if (!data) {
return <div>Loading...</div>;
}
return (
<div>
<h1>Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default MyComponent;
Top comments (0)