下面是一个使用Jest来测试将一个属性添加到响应头中的示例代码:
首先,安装所需的依赖项。在命令行中运行以下命令:
npm install jest axios
然后,创建一个名为api.js
的文件,并添加以下代码:
import axios from 'axios';
export const fetchData = async () => {
const response = await axios.get('https://api.example.com/data');
// 添加自定义属性到响应头中
response.headers['Custom-Header'] = 'Custom Value';
return response;
};
接下来,创建一个名为api.test.js
的文件,并添加以下代码:
import axios from 'axios';
import { fetchData } from './api';
jest.mock('axios');
describe('fetchData', () => {
it('should add a custom header to the response', async () => {
const mockResponse = {
data: {},
headers: {}
};
axios.get.mockResolvedValue(mockResponse);
const response = await fetchData();
expect(response.headers['Custom-Header']).toBe('Custom Value');
});
});
在上述代码中,我们首先通过使用jest.mock
来模拟axios
模块。然后,在测试用例中,我们设置了axios.get
的模拟返回值为一个包含空数据和空响应头的对象。接下来,我们调用fetchData
函数,并断言返回的响应头中的Custom-Header
属性的值是否为Custom Value
。
最后,运行以下命令来运行测试:
npx jest
Jest将执行测试并输出结果。如果一切正常,你应该会看到测试通过的消息。