Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
Manual mock a factory function

I have a common use case where I have an in-code API client:

// services/getApiClient.js

import axios from 'axios';

export default (user) => {
  return axios.get('https://api.com', headers: { Authorization: user.apiKey });
}

My app consumes this API client in lots of routes.

I want to be able to use a manual mock defined in 1 file throughout my Jest test suite:

// services/__mocks__/getApiClient.js

export const get = jest.fn();
export const post = jest.fn();

export default (user) => {
  return {
    __esMock: true,
    default: {
       get,
       post
    }

  }
}

Then I was hoping to be able to pull this off in tests:

// example.test.js

import getApiClient from 'services/getApiClient'
import { get } from 'services/__mocks__/getApiClient';
jest.mock('services/getApiClient');

get.mockReturnValue({ data: { example: 'data' });

However, when example.test.js is executing the real subject example.js, the mocked return value of apiClient.get is always undefined.

I know I can get this test working by performing a jest.mock with an inline replacement, but it's a lot of copying and pasting I'm hoping to avoid.

// example.test.js

import getApiClient from 'services/getApiClient';
jest.mock('services/getApiClient');

const apiClient = {
   get: jest.fn(),
   post: jest.fn()
};

jest.mockImplementation(() => apiClient);

apiClient.get.mockReturnValue({ data: { example: 'data' }});

Any guidance on making these mocks more DRY would be appreciated!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!