如何从模块中为特定测试(Jest)模拟特定功能

时间:2018-07-27 23:01:15

标签: testing jestjs

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

// 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)

有人知道如何使我之前的测试失败才能通过吗?谢谢您的宝贵时间。

1 个答案:

答案 0 :(得分:0)

您需要创建makeFetch的模拟。您可以使用spyOnmockReturnValue来做到这一点。

您需要将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();
  });
});