-1

I am writing tests for functions in a file. Several functions call another function which is also in that file. Here is how it looks:

function importantFunc(str) {
  //some logic
  return result;
}

function funcA() {
  //some logic
  const result = importantFunc('test A')
  //some logic
}

function funcB() {
  //some logic
  const result = importantFunc('test B')
  //some logic
}

I have already written a test for importantFunc. Problem is how can I test mock the call to importantFunc in funcA and funcB so that they will not call importantFunc directly, but use the result I provide in my mock?

Between jest.spyOn and jest.fn, I am thinking jest.fn may work. But I cannot figure out how it will tie to funcA or funcB.

Farhan
  • 2,535
  • 4
  • 32
  • 54
  • Specifically https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest/70066090#70066090, which is to say: don't. – jonrsharpe Jan 19 '23 at 20:47

1 Answers1

0

You generally can't, unless if you're importing importantFunc from another module, in which case you mock the whole module.

What you should do is refactor your code so your units are not tightly coupled to one-another.

// in impl
function funcA(importantFunc) {
  //some logic
  const result = importantFunc('test A')
  //some logic
}

function funcB(importantFunc) {
  //some logic
  const result = importantFunc('test B')
  //some logic
}

// ...
// ...

// in test
const importantFunc = jest.fn(() => { ... });
funcB(importantFunc)
Slava Knyazev
  • 5,377
  • 1
  • 22
  • 43