jest icon indicating copy to clipboard operation
jest copied to clipboard

Mocking doesn't work with aliases set in jsc.paths

Open abejfehr opened this issue 11 months ago • 2 comments

I can get jsc.paths working just fine and resolving things, for example this jest config and test:

export const config = {
  transform: {
    '\\.(ts|tsx)$': [
      '@swc/jest',
      {
        jsc: {
          baseUrl: '.',
          paths: {
            '@monorepo/some-library': ['libs/some-library/src/index.ts'],
          },
        },
      },
    ],
  },
};

export default config;
import { CONSTANT } from '@monorepo/some-library';

describe('adding', () => {
  it('works', () => {
    console.log({ CONSTANT });

    expect(1 + 1).toBe(2);
  });
});

^ the constant logs in the console just fine

but as soon as I try to mock the local library, I get an error. Here's an updated test:

import { CONSTANT } from '@monorepo/some-library';

jest.mock('@monorepo/some-library', () => ({ CONSTANT: 'stubbed constant' }));

describe('adding', () => {
  it('works', () => {
    console.log({ CONSTANT });

    expect(1 + 1).toBe(2);
  });
});

I get the following output:

 FAIL  just-a-test/adding.test.ts
  ● Test suite failed to run

    Cannot find module '@monorepo/some-library' from 'adding.test.ts'

      1 | import { CONSTANT } from '@monorepo/some-library';
      2 |
    > 3 | jest.mock('@monorepo/some-library', () => ({ CONSTANT: 'stubbed constant' }));
        |      ^
      4 |
      5 | describe('adding', () => {
      6 |   it('works', () => {

      at Resolver._throwModNotFoundError (../node_modules/jest-resolve/build/resolver.js:427:11)
      at Object.<anonymous> (adding.test.ts:3:6)

using babel as a transformer with their module resolver plugin this situation seems to work okay.

abejfehr avatar Jan 05 '25 17:01 abejfehr

Ah, it works with babel because by default they transform the first argument in jest.mock as if it's an import: https://github.com/tleunen/babel-plugin-module-resolver/blob/620df49418e07aab1f5f3d668b02e56b27b89e94/DOCS.md?plain=1#L163

It would be great if the SWC jest transformer had this functionality too

abejfehr avatar Jan 05 '25 17:01 abejfehr

It seems like require() statements don't get rewritten either, leading to Cannot find module ... errors in jest for that too

abejfehr avatar Jan 05 '25 19:01 abejfehr