vendredi 27 juillet 2018

How do I mock a specific function from a module for a specific test

I have an api.js file that contains my api call. It looks like this:

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

Then I have an api.test.js file that looks like:

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

this is the error I get:

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)

Does anyone know how to make this pass with making my previous tests fail? Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire