'How to mock global Object with Jest in React Native

I have the function:

const someFn = () => {
  const keys = Object.keys(someObj);
  // rest of function
}

In my unit test (with jest), I want to mock the return value of Object.keys:

test('some test', () => {
  jest.mocked(Object.keys).mockReturnValue(['one', 'two']);
  // rest of test
});

But that resulting the following error:

TypeError: jest.mocked(...).mockReturnValue is not a function

Usually It means that I need to first mock the export itself using jest.mock, but with global Object I'm not sure how to do it. I thought maybe:

global.Object = {
  keys: jest.fn(),
}

But that doesn't seem to work at all.

Any idea how to solve this issue? thanks :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source