Skip to content Skip to sidebar Skip to footer

Javascript Mock A Variable Inside A Method

I have this object: I want to mock the key variable with a mock value. I tried: ... but i can't mock the key variable. How to mock that variable from my function?

Solution 1:

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: asyncfunction(url, getAccess = keys.getAccess) {
    const key = await getAccess()

    returnget(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) => {
    returnget(url, {secret: "my-mocked-key"})
  });

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

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

Post a Comment for "Javascript Mock A Variable Inside A Method"