您好,登錄后才能下訂單哦!
在Jest框架中,我們可以使用jest.mock()
方法來模擬HTTP請求
npm install axios
api.js
的文件,其中包含一個(gè)使用axios發(fā)送GET請求的函數(shù):// api.js
import axios from 'axios';
export async function fetchData(url) {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
api.test.js
的測試文件:// api.test.js
import axios from 'axios';
import { fetchData } from './api';
jest.mock('axios');
describe('fetchData', () => {
it('should return data from the API', async () => {
const url = 'https://api.example.com/data';
const expectedData = { key: 'value' };
// 模擬axios.get()返回的Promise
axios.get.mockResolvedValue({ data: expectedData });
const data = await fetchData(url);
expect(axios.get).toHaveBeenCalledWith(url);
expect(data).toEqual(expectedData);
});
it('should handle errors', async () => {
const url = 'https://api.example.com/data';
const errorMessage = 'Network Error';
// 模擬axios.get()返回的Promise
axios.get.mockRejectedValue(new Error(errorMessage));
try {
await fetchData(url);
} catch (error) {
expect(axios.get).toHaveBeenCalledWith(url);
expect(error.message).toEqual(errorMessage);
}
});
});
在這個(gè)例子中,我們使用jest.mock('axios')
來模擬axios庫。然后,在測試用例中,我們使用axios.get.mockResolvedValue()
和axios.get.mockRejectedValue()
來模擬成功和失敗的HTTP請求。這樣,我們就可以在不實(shí)際發(fā)送網(wǎng)絡(luò)請求的情況下測試fetchData
函數(shù)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。