溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Jest框架中模擬HTTP請求

發(fā)布時(shí)間:2024-08-28 10:17:51 來源:億速云 閱讀:83 作者:小樊 欄目:編程語言

在Jest框架中,我們可以使用jest.mock()方法來模擬HTTP請求

  1. 首先,安裝axios庫:
npm install axios
  1. 創(chuàng)建一個(gè)名為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;
  }
}
  1. 創(chuàng)建一個(gè)名為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ù)。

向AI問一下細(xì)節(jié)

免責(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)容。

AI