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

156
Visualizações
Javascript mock a variable inside a method

I have this object:

import keys from './keys'
const obj = {
  getData: async funcion(url) {
    const key = await keys.getAccess()

    return get(url, {
        secret: key
      }
    })
}
}

I want to mock the key variable with a mock value. I tried:

test('test', async() => {
  const spyD = jest.spyOn(obj, 'getData');
  expect(obj.getData).toHaveBeenCalledWith('/url', {secret: 'my mocked key') //but secret is undefined
})

... but i can't mock the key variable. How to mock that variable from my function?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can't directly; the scope is closed over, there is no way to gain access to a variable declared within it. You can pass in the function that creates key instead so that you can mock its implementation, while passing the original function as a default:

const obj = {
  getData: async function(url, getAccess = keys.getAccess) {
    const key = await getAccess()

    return get(url, {
        secret: key
      }
    })
  }
}
test('test', async () => {
  const spyD = jest.spyOn(obj, 'getData');

  const result = await obj.getData("/url", async () => "my mocked key");

  expect(spyD).toHaveBeenCalledWith("/url");
})

This test should now pass, and result will be the return value of get called with "/url" and {secret: "my mocked key"}.

Alternatively, if you would prefer not to modify obj, you can mock the implementation of getData altogether to get the same result:

test('test', async () => {
  const spyD = jest.spyOn(obj, 'getData').mockImplementation(async (url) => {
    return get(url, {secret: "my-mocked-key"})
  });

  const result = await obj.getData("/url");

  expect(spyD).toHaveBeenCalledWith("/url");
})
about 4 years ago · Juan Pablo Isaza Relatório
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