0

There are many questions on StackOverflow about how to mock things with Jest. I have, indeed, read many of those suggestions. I have experience with jest.mock and spyOn. I've tried the trick of doing a real import and overwriting just the function I desire to mock and have also tried the old import * as math from './math.js' and then you try to spyOn math but if you try it, you'll see that this won't work.

But after quite a lot of experimentation, I'm beginning to conclude that this is fundamentally impossible (which actually feels correct to me). The "real" subtract function that calls add will only ever be able to call the add defined in that module.

KEY POINT: The math.js file can NOT be edited. You cannot change it so that you have add and subtract as properties hanging off of some object. Consider that the math.js file is etched in stone and cannot be modified in any way.

I would LOVE to be wrong about this, but it seems to me that the free-standing add function in the math.js file cannot be mocked such that when you call the "real" subtract function, it runs the mocked add function. I know you could mock add and have mock add call a mocked subtract, but that is not the goal here.

Please consider this a purely academic question. This is not an XY problem. This is not a case of "what are you trying to do; there is a better way." This is purely trying to understand how things work given the fixed constraints I've outline in the question. Thanks!

math.js

export function add(a, b) {
   return a+b;
}

export function subtract(a, b) {
   return add(a, -b);
}

math.test.js

import { subtract } from './math.js';

// mock the add function to return 1234

describe('math', () => {
   it('should return 1234', () => {
      expect(subtract(5,3)).toBe(1234);
   });
});
sstchur
  • 1,883
  • 2
  • 9
  • 10
  • Does this answer your question? [How to mock functions in the same module using Jest?](https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest) – jonrsharpe Dec 03 '22 at 22:16
  • Specifically: [don't](https://stackoverflow.com/a/70066090/3001761). – jonrsharpe Dec 03 '22 at 22:17
  • Kind of. Wasn't looking for a solution. My question was purely academic to ensure that scoping of module imports/exports worked as I believed they did. I've chosen the answer given by Necati Turan as accepted because he verifies what I believed to be true in his first sentence. The rest of the answer wasn't really necessary (for me); I was already aware of alternatives, but it may be helpful for future readers. Thanks to you both! – sstchur Dec 05 '22 at 16:57
  • Hey, what happened to Necati Turan's answer? I chose that as accepted answer, and now it appears to have disappeared. Can we get that back please? – sstchur Dec 16 '22 at 16:57

0 Answers0