jest mock json code example

Example 1: jest axios manual mock

//axios.js
const axios = require('axios')
module.exports = axios.get

//__mocks__/axios.js
const axios = require('axios')

module.exports = {
  get: async () => {
  const url = 'https://jsonplaceholder.typicode.com/posts'
  const response = await axios.get(url)
  return response.data
  }
}

//__test__/axios.test.js
const axiosMock = require('../axios')

test('async axios action users with mock', async (done) => {
  const url = 'https://jsonplaceholder.typicode.com/users'
  response = await axiosMock(url)

  expect(response).toBeDefined()
  expect(response.length).toBe(100);
  done()
});

Example 2: how to mock a library in jest

import randomColor from "randomcolor";


jest.mock("randomColor", () => {
  return {
    randomColor: () => {
      return mockColor('#123456');
    }
  }
});
let mockColor = jest.fn();