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?
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");
})