-1

Given a JS file like this:

export const uid = () => Math.random().toString();
export const doubleUid = () => [uid(),uid()].join('_');

How can you use Jest to mock uid as () => 'foo' such that the result of doubleUid() is foo_foo? Is it possible to do so without modifying the file above?

bjnsn
  • 2,710
  • 2
  • 16
  • 14
  • 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 Apr 13 '23 at 08:36
  • Specifically https://stackoverflow.com/a/70066090/3001761, which is to say: don't. – jonrsharpe Apr 13 '23 at 08:36
  • I've edited my question to clarify that I'm asking how to do it 'without modifying the file' . The referenced issue doesn't answer that – all of the suggestions either involve modifying the file to test OR rely on the tested code already be deterministic. – bjnsn Apr 14 '23 at 15:24
  • You already _shouldn't_, but without modifying the file you _can't_. – jonrsharpe Apr 14 '23 at 15:25
  • Update – one of the comments does mention babel-rewire-plugin – which could solve this for some people depending on their stack https://stackoverflow.com/a/52725067/3758164 – bjnsn Apr 14 '23 at 15:38

1 Answers1

1

I'm not aware of any way to do this using mocks.

You have to mock each exported function separately. Mocking the exported version of the first function doesn't change the original implementation of the second exported function.

See this answer I gave to a related sort of question here: https://stackoverflow.com/a/72192912/3084820

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30