Skip to content
This repository has been archived by the owner on Jan 16, 2025. It is now read-only.

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

Open
abejfehr opened this issue Jan 5, 2025 · 2 comments
Open

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

abejfehr opened this issue Jan 5, 2025 · 2 comments

Comments

@abejfehr
Copy link

abejfehr commented Jan 5, 2025

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
Copy link
Author

abejfehr commented Jan 5, 2025

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
Copy link
Author

abejfehr commented Jan 5, 2025

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

1 participant