0

I am attempting to mock an object that is referenced by my method with jest. I would like to change the value of the referenced object to something else for testing.

example:

External function and object

// ./external.js

export const functionToTest() {
   const object = objectIWantToMock;
   return 'result using object';
}

export const objectIWantToMock = {
    stuff: {}
}

test file:

// ./external.test.js

explain('when object is different', () => {
   it('should do something different', () => {
       // how to mock object when it is called by functionToTest?
   })
})
Dzone64
  • 98
  • 7
  • Have you tried mocking it like you normally would? There are a few exceptions such as `localStorage`, but most `global` and "external dependencies" can be mocked normally. – Urmzd Nov 27 '21 at 17:20
  • @Urmzd yes. something along the lines of `jest.mock('../external.js', () => ({stuff2: {}}))`. The function seems to be unaware of the mock. – Dzone64 Nov 27 '21 at 17:35
  • Did you import it? You're just doing `'./external.test.js'`, which does nothing. You have to import the file... `import './external.test.js'` – Urmzd Nov 27 '21 at 21:06
  • Or is that meant to be a comment? – Urmzd Nov 27 '21 at 21:07
  • just a comment. – Dzone64 Nov 27 '21 at 22:22
  • Can you provide the structure of your project (the relation of the two files)? Attempting to reproduce the error, and go from there. – Urmzd Nov 27 '21 at 22:50
  • 2
    I think I figured out the problem, as stated [here](https://stackoverflow.com/questions/51269431/jest-mock-inner-function), I guess it isn't possible to mock two separate exports because the first function is referencing the object directly instead of through an import. I refactored them into separate modules and the mock worked. – Dzone64 Nov 27 '21 at 23:57
  • Glad to hear it, you should probably change your title and description to better reflect the problem (which would something along the lines of `how to mock export in same file`) – Urmzd Nov 28 '21 at 01:39

0 Answers0