Search code examples
javascripttypescriptjestjsts-jest

jest.mock not working with Javascript test and Typescript module


My mocked utilFunction isn't being used and adding logging to the factory function shows that it's never called. I've already tried searching for jest.mock not working with relative paths and jest.mock not being called for Typescript thinking that it might be related to the mix of JS tests and TS source code or to the different module paths used in the source vs test code.

Code being tested:

// src/foo/fooModule.ts
import { utilFunction } from '../util'

export const foo = () => {
  return utilFunction()
}

Test code:

// test/fooModule.test.js
const { foo } = require('../src/foo/fooModule')

jest.mock('../src/util', () => {
  return { utilFunction: () => 'mocked' };
});

describe('fooModule tests', () => ...)

Solution

  • The jest.mock call needs to be moved above the imports:

    // test/fooModule.test.js
    jest.mock('../src/util', () => {
      return { utilFunction: () => 'mocked' };
    });
    
    const { foo } = require('../src/foo/fooModule')
    
    
    describe('fooModule tests', () => ...)
    

    My last experience working with Jest prior to this was in a project where the tests were also written in Typescript and babel-jest was used. babel-jest includes babel-jest-hoist which hoists the jest mocks above any imports automatically, so I didn't previously have to worry about the ordering.