Testing 如何为特定测试(Jest)模拟模块中的特定函数

Testing 如何为特定测试(Jest)模拟模块中的特定函数,testing,jestjs,Testing,Jestjs,我有一个包含api调用的api.js文件。看起来是这样的: // api.js // reusable fetch call export const makeFetch = async (url, options) => { try { const response = await fetch(url, options); if (!response.ok) { throw new Error(`${response.status}`); }

我有一个包含api调用的api.js文件。看起来是这样的:

// api.js

// reusable fetch call
export const makeFetch = async (url, options) => {
  try {
    const response = await fetch(url, options);

    if (!response.ok) {
      throw new Error(`${response.status}`);
    }

    return await response.json();
  } catch (error) {
    throw new Error(`Network request failed. (error: ${error.message})`);
  }
};

// actual fetch call
export const getCards = async () => {
  const url = 'http://localhost:3001/api/v1/cards';
  return await makeFetch(url);
};
然后我有一个api.test.js文件,看起来像:

//api.test.js

import { makeFetch, getCards } from './api';

describe('makeFetch', () => {

  // three successful tests

});

// this is where I have issues

describe('getCards', () => {
  it('calls makeFetch', async () => {

    await getCards();

    expect(makeFetch).toHaveBeenCalledTimes(1);
  });
});
这是我得到的错误:

FAIL  src\api\api.test.js
  ● getCards › calls makeFetch

    ReferenceError: makeFetch is not defined

      at Object.it.only (src/api/api.test.js:51:15)
          at new Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:182:7)
src\api\api.test.js失败
● getCards›调用makeFetch
ReferenceError:未定义makeFetch
仅限于Object.it(src/api/api.test.js:51:15)
在新的承诺()
在Promise.resolve.then.el(node_modules/p-map/index.js:46:16)
在
在进程中。_tick回调(internal/process/next_tick.js:182:7)

有人知道如何让我以前的测试失败而通过吗?谢谢您的时间。

您需要创建makeFetch的模拟。你可以用和来做

您需要将makeFetch移动到它自己的文件(lib.js)中,以便在测试中模拟并替换它:

// ---- lib.js ----
// reusable fetch call
export const makeFetch = async (url, options) => {
  try {
    const response = await fetch(url, options);

    if (!response.ok) {
      throw new Error(`${response.status}`);
    }

    return await response.json();
  } catch (error) {
    throw new Error(`Network request failed. (error: ${error.message})`);
  }
};



// ---- api.js ----
import { makeFetch } from './lib';

// actual fetch call
export const getCards = async () => {
  const url = 'http://localhost:3001/api/v1/cards';
  return await makeFetch(url);
};



// ---- api.test.js ----
import * as lib from './lib';
import { getCards } from './api';

describe('makeFetch', () => {

  // three successful tests

});

describe('getCards', () => {
  it('calls makeFetch', async () => {
    const simulatedResponse = { data: 'simulated response' };

    // mock makeFetch
    const mock = jest.spyOn(lib, 'makeFetch');
    mock.mockReturnValue(Promise.resolve(simulatedResponse));

    const result = await getCards();

    expect(result).toEqual(simulatedResponse);
    expect(mock).toHaveBeenCalledTimes(1);
    expect(mock).toHaveBeenCalledWith('http://localhost:3001/api/v1/cards');

    // restore makeFetch
    mock.mockRestore();
  });
});

感谢您的响应,但在运行此程序时,如果我将该行更改为:“mock.mockImplementationOnce(()=>Promise.resolve(simulatedResponse));”测试响应将变为:预期值等于:{“data”:“simulatedResponse”}接收:[[Object],[对象],…]啊,你使用的是早期版本的Jest,我会在几分钟内更新我的答案!你是最棒的。我使用的是create react应用程序,所以我猜其中包含的Jest版本很旧。非常感谢你的帮助我很高兴,很高兴它帮助了我,谢谢。完成。(我投了赞成票,但因为我的声誉<15,所以它不会显示出来)