0

I am having an issue with mocking functions called from within my module. when the mocked function is called from the test, it works as expected. but when that same mocked function is called from the library, it calls the actual function.

I have tried the jest.mock('./myModule', () => {}) approach, and enableAutomock as well, but with the same results.

I feel like i have not had this problem in other projects, but have looked through my jest configuration, and don't see anything that would effect it.

what am i missing here? how can i mock functions called internally within my module?

// myModule.js

export function foo() {
  return 'foo'
}

export function bar() {
  return foo()
}
// myModule.test.js
import * as myModule from './myModule';

jest.spyOn(myModule, 'foo').mockReturnValue('mock foo');

// i have also tried...
// jest.mock('./myModule', () => {
//   ...(jest.requireActual('./myModule')),
//   foo: jest.fn().mockReturnValue('mock foo')
// });

it('should', () => {
  expect(myModule.foo()).toEqual('mock foo'); // PASS: returns 'mock foo'
  expect(myModule.bar()).toEqual('mock foo'); // FAIL: returns 'foo'
});
brewster
  • 4,342
  • 6
  • 45
  • 67
  • Does this answer your question? https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest – Lin Du Mar 29 '22 at 03:49
  • 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 Mar 29 '22 at 07:44
  • I'd particularly highlight https://stackoverflow.com/a/70066090/3001761, of course. – jonrsharpe Mar 29 '22 at 07:45
  • i ran through that thread, but none of it worked. even the solution posted to the jest github issues https://github.com/facebook/jest/issues/936, and with using an arrow function `export const foo = () => {}` – brewster Mar 29 '22 at 18:09
  • so i found that using `ts-jest` for my jest transform, makes mocking behave as expected, and those tests now pass – brewster Mar 29 '22 at 20:56

1 Answers1

0

I found using ts-jest in my jest config, allowed these tests to run as i expected

transform: {
  '^.+\\.[tj]sx?$': ['ts-jest'],
},
brewster
  • 4,342
  • 6
  • 45
  • 67