Julian Mendez
Julian Mendez

Reputation: 3380

JEST Mocking from node modules

I have been trying this for a while and i couldn't find the solution.

I tried a lot of solutions (__ mock __ folder, mockimplementation, mock and more) but i always had the same error client.mockImplementation is not a function

//restclient.js

module.exports = (cfg) => new Client(config);
// api.js
const client = require('restclient');
module.exports.doRequest = () => {
    const request = client();
    const config = {};
    request.get('/path/to/request', config)
    .then(result => console.log(result))
}
//api.tests.js
const client = require('restclient');
const api = require('./api');

jest.mock('restclient', () => () => ({
  get: jest.fn(),
}));
  describe('testing API', () => {
    test('test then', async () => {
      try {
        restclient.mockImplementation(() => () => ({
          get: (url, config) => 'Hi! I\'m mocked',
        }));
        const result = await api.doRequest();
        console.log('result', result);
      } catch (e) {
        console.log('eee', e);
      }
    });
  });

I could not found the solution, I think I can't mock the const request = restclient() part but i dont know why!!

Upvotes: 0

Views: 450

Answers (1)

Francesc Montserrat
Francesc Montserrat

Reputation: 349

You were missing to mock the constructor.

This mocks the constructor of restclient

jest.mock('restclient', ()=> jest.fn().mockImplementation(() => {

 /** here you can create and return a mock of request **/

}));

Upvotes: 2

Related Questions