I am unable to get jest.mock to actually mock a mo...
# help
r
I am unable to get jest.mock to actually mock a module in my sst TypeScript app. The repo is setup as a monorepo.
Copy code
// foo.test.ts
import { create } from './service';
jest.mock('./service');
console.log(create); 
// logs [AsyncFunction: create] instead of [Function: mockConstructor]
We are using ts-jest and esbuild-runner. Here is jest.config.js:
Copy code
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*.test.(ts|tsx|js)'],
  testPathIgnorePatterns: ['node_modules', 'build'],
  transform: {
    '\\.ts$': 'esbuild-runner/jest',
  },
}
There is a jest issue that says you can’t mock modules without using Babel, but doesn’t esbuild-runner/jest handle that? Mocking modules is so common in jest that I’m surprised this isn’t working. There must be something I’m missing in our setup??
Well, more experimenting and I seem to have fixed it. I had
module: "esnext"
. Switched it to
module: "commonjs"
and now mocking works. I’m not sure how I ended up with “nextjs”. I also had to remove “transform” from my jest.config.js, and remove ts-jest type checking with
isolatedModules: true
since it now no longer recognizes my
moduleNameMapper
settings (that were working before all these changes).
f
@Robert Gardner glad u got it working. Thanks for sharing!