Not able to access variables in jest.mock function

Viewed 3955

Please check below scenario

const url = 'https://mock.com/mockpath';
jest.mock('../../src/somefile', () => {
  return ({
    getURL: jest.fn(() => url),
  });
});

I am getting error

babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: url
2 Answers

Courtesy @skyboyer

Just renamed url to mockUrl, any variable starting with mock is accessible inside jest.mock.

@skyboyer thanks again for the help.

'jest.mock()' is not allowed to reference any out-of-scope variables. Invalid variable access: mockURL

It's telling you that jest.mock() is trying to access mockURL, but it is not allowed to access an out-of-scope variable.

You should declare mockURL inside the jest.mock() function call:

jest.mock('../../src/somefile', () => {
  const mockURL = 'https://mock.com/mockpath';
  return ({
    getURL: jest.fn(() => mockURL),
  });
});

Or you could just reference the string without using the intermediate variable:

jest.mock('../../src/somefile', () => ({
  getURL: jest.fn(() => 'https://mock.com/mockpath'),
}));
Related