'How to mock a function using Frisby and Jest to return custom response?

I'm trying to mock a function using Frisby and Jest. Here are some details about my code:

dependencies axios: "^0.26.0", dotenv: "^16.0.0", express: "^4.17.2"

devDependencies frisby: "^2.1.3", jest: "^27.5.1"

When I mock using Jest, the correct response from API is returned, but I don't want it. I want to return a fake result like this: { a: 'b' }.

How to solve it?

I have the following code:

// (API Fetch file) backend/api/fetchBtcCurrency.js
const axios = require('axios');

const URL = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json';

const getCurrency = async () => {
  const response = await axios.get(URL);
  return response.data;
};

module.exports = {
  getCurrency,
};
// (Model using fetch file) backend/model/cryptoModel.js
const fetchBtcCurrency = require('../api/fetchBtcCurrency');

const getBtcCurrency = async () => {
  const responseFromApi = await fetchBtcCurrency.getCurrency();
  return responseFromApi;
};

module.exports = {
  getBtcCurrency,
};

// (My test file) /backend/__tests__/cryptoBtc.test.js
require("dotenv").config();
const frisby = require("frisby");
const URL = "http://localhost:4000/";

describe("Testing GET /api/crypto/btc", () => {

  beforeEach(() => {
    jest.mock('../api/fetchBtcCurrency');
  });

  it('Verify if returns correct response with status code 200', async () => {
    const fetchBtcCurrency = require('../api/fetchBtcCurrency').getCurrency;
    
    fetchBtcCurrency.mockImplementation(() => (JSON.stringify({ a: 'b'})));

    const defaultExport = await fetchBtcCurrency();
    expect(defaultExport).toBe(JSON.stringify({ a: 'b'})); // This assert works

    await frisby
      .get(`${URL}api/crypto/btc`)
      .expect('status', 200)
      .expect('json', { a: 'b'}); // Integration test with Frisby does not work correctly.
  });
});
Response[
  {
    I hid the lines to save screen space.
  }
 ->>>>>>> does not contain provided JSON [ {"a":"b"} ]
];


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source