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

154
Views
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 answers
Answer question

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 Report
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!