1

I have a module which contains two functions where function A calls function B. I only want to mock function B because it's doing some hard to test logic, but keep function A unmocked.

Functions:

export functionB = () => {

}

export functionA = () => {
    return functionB()
}

I know I can update the original file like this but this seems messy to me.

functionB = () => {

}

functionA = () => {
    return exportFunctions.functionB()
}

const exportFunctions = {
  functionA,
  functionB
};

export default exportFunctions;

I'm doing:

jest.mock("functions", () => ({
      ...(jest.requireActual("functions") as object),
      functionB: jest.fn()
}))

But when I test functionA, it's still calling the actual functionB implementation which makes sense. But I don't know how to inject a new definition of functionB into the call without rewriting the function in a mock. Is this possible?

Thanks in advance!

Joey
  • 11
  • 3
  • It 's impossible to mock a function that is used in the same module it's defined. What you did with exportFunctions is the only workaround that is available in Jest. Either split a module, or treat them as a single unit. – Estus Flask Dec 12 '20 at 22:03
  • Does this answer your question? [Jest mock inner function](https://stackoverflow.com/questions/51269431/jest-mock-inner-function) – Lin Du Dec 14 '20 at 05:30
  • Yes actually, thank you! This is really helpful – Joey Dec 14 '20 at 17:03

0 Answers0