Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda