首页 > 解决方案 > 如何模拟调用 fetch() 并返回响应 obj 的函数?

问题描述

export const fetchSomeData = async (): Promise<DataInterface> => {
  try {
    const url = `/api/someRoute`;
    const res = await fnThatCallsFetch({
      url,
      method: 'GET'
    });
    const resData = await res.json();
    const someData= resData.data;

    if (res.status === 200 && someData) {
      return someData;
    } else {
      
      throw new Error('Could not fetch info');
    }
  } catch (e) {
     
    throw e;
  }
};

fnThatCallsFetch 是一个调用 fetch() 的函数。如何模拟 fnThatCallsFetch 使其返回一些模拟数据?

目前我正在寻找间谍,但我不知道如何模拟响应对象,因为打字稿不会让我只模拟 json()。

const spyOn = jest.spyOn(fetchFn, 'fnThatCallsFetch').mockResolvedValue({
        json: jest.fn().mockResolvedValue({
            data: { name: '006-100' }
        })
    })

    const data = await fetchSomeData ();

    expect(data).toEqual({ name: '006-100' });

标签: jestjs

解决方案


推荐阅读