aleclarson / vite-tsconfig-paths

Support for TypeScript's path mapping in Vite
MIT License
1.23k stars 44 forks source link

Path options do not work with `vitest` `vi.mock` #99

Closed haakonjackfloat closed 1 year ago

haakonjackfloat commented 1 year ago

Given a tsconfig.json like so:

{
  "compilerOptions": {
    "baseUrl": "./app",
    "paths": {
      "@c/*": ["../../common/src/*"],
    }
  },
  "include": ["app/**/*"],
}

And a vite.config.ts:

import path from 'path';
import { defineConfig } from 'vitest/config';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  test: {
    globals: true,
    setupFiles: path.resolve(__dirname, 'testSetup'),
  },
  plugins: [tsconfigPaths() as any],
});

In a vitest spec file:

import { someMethod } from '@c/some/lib';

// This does not work, `someMethod` will not be a spy
vi.mock('@c/some/lib', () => {
  return {
    someMethod: vi.fn(),
  };
});

// This does work
vi.mock('../../common/src/some/lib', () => {
  return {
    someMethod: vi.fn(),
  };
});
tb-viktor commented 1 year ago

Encountering this problem as well.

In our case we don't have any specific paths declared in our tsconfig, but just use the tsconfigPaths() plugin to shorten import paths from the base url. As above, vi.mock does not resolve it properly. When we change the mock path from e.g. folder1/folder2/file to /baseUrl/folder1/folder2/file explicitly it works, but it is not ideal and makes migration from jest somewhat tedious with a large amount of test files.

DanHulton commented 1 year ago

This may be related... I have vite-tsconfig-paths set up nearly exactly the same as above (js file for vite.config, but otherwise the same), and I have been unable to get dynamic imports to work when running vitest.

import { configurePassport } from '#api/Passport'; works, but const { configurePassport} = import('#api/Passport'); will not, with the error Error: Failed to load url #api/Passport (resolved id: #api/Passport). Does the file exist?

These imports work just fine when running the app via vite-node, it's just in vitest that they no longer resolve.

Potentially the same code path doing the resolving for dynamic imports as trying to resolve mocks? I haven't seen much discussion of vitest resolution issues outside of this specific issue.

cayter commented 1 year ago

It's a vitest bug and they just reverted the commit in v0.28.4 about an hour ago.

DanHulton commented 1 year ago

TYVM, @cayter! It turns it these two were related. Updated to vitest 0.28.4 and the issue with dynamic imports is fixed as well!

haakonjackfloat commented 1 year ago

Indeed, looks fixed! Thanks for the heads up @cayter!