Vitest - @ src folder alias not resolved in test files
Asked Answered
P

5

49

I have a vue3 project using Vite/Vitest, as recommanded in Vue.js documentation.

Here is the structure of the project:

src
  components
    // my Vue components here, potentially in sub-folders. For example:
    HelloWorld.vue 
  router
    index.ts
  App.vue
  main.ts
vitest
  components
    // My test specs. For example:
    HelloWorld.spec.ts
// ...
tsconfig.app.json
tsconfig.json
tsconfig.vite-config.json
tsconfig.vitest.json
vite.config.ts

The @/ alias for src folder is resolved properly in components files. However, in my test files, I get an error: cannot find module.

For example, in HelloWorld.spec.ts:

import HelloWorld from '@/components/HelloWorld.vue'; // <-- error !
import { describe, it } from 'vitest';

describe('HelloWorld', () => {
  it('should day hello', () => {
    // ...
  });
});

tsconfig.app.json

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": [
    "env.d.ts",
    "src/**/*",
    "src/**/*.vue"
  ],
  "exclude": [
    "vitest/**/*"
  ],
  "compilerOptions": {
    "composite": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    },
    "strict": true,
    "experimentalDecorators": true
  }
}

vite.config.js

import vue from '@vitejs/plugin-vue';
import { fileURLToPath, URL } from 'url';
import { defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  test: {
    include: ['./vitest/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
  },
});
Prearrange answered 1/6, 2022 at 21:28 Comment(10)
You could first try with a more standarized way to build aliases in vite.config.js: alias: { "@": "./src" } . If it's not working, or if you want to keep the same config, I suggest you to publish a reproducible project.Rohr
The alias config came as-is with the initialization of the project, using npm init vue@latest. But I tried other configs and none is working.Prearrange
Yes - then you should give us a reproducible project, i suspect a typescript config issue or it could be also possible that you hit a recent issue which require the project to be built at least one time before setting the test.include.Rohr
Do you also use a vitest.config.js file?Bantu
no, I don't use a specific config file for vitestPrearrange
Any idea why we should exclude test files in tsconfig.app.json? Because including this files instead of excluding them solves the problem.Prearrange
The reason is to avoid these files being compiled. You can be more "precise" about what you want to do with these files by using the typescript configurations option.Rohr
why is it a problem if the tests files are compiled?Prearrange
same prob for me also. I tried to configure the resolve.alias vite config property but it still not workingMarquittamarr
@AdriHM, look at my comment of June 13. It may help.Prearrange
P
3

The final solution that worked for me was to include the test files in tsconfig.vitest.json:

tsconfig.app.json (unchanged from question post)

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": [
    "env.d.ts",
    "src/**/*",
    "src/**/*.vue"
  ],
  "exclude": [
    "vitest/**/*"
  ],
  "compilerOptions": {
    "composite": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    },
    "strict": true,
    "experimentalDecorators": true
  }
}

tsconfig.vitest.json

{
  "extends": "./tsconfig.app.json",
  "include": [
    "vitest/**/*",
  ],
  "exclude": [],
  "compilerOptions": {
    "composite": true,
    "lib": [],
    "types": [
      "node",
      "jsdom"
    ],
  }
}
Prearrange answered 25/1, 2023 at 16:10 Comment(1)
Yep, worked for me as well, like include=[...., "test"] in the regular tsconfing.app.jsonMural
M
69

You just have to specify the aliases in your vitest.config.js file:

import path from 'path'
import vue from '@vitejs/plugin-vue'

export default {
  plugins: [vue()],
  test: {
    globals: true,
    environment: 'jsdom',
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    },
  },
}
Marquittamarr answered 17/7, 2022 at 17:43 Comment(5)
I guess it should be '@': path.resolve(__dirname, './src'),Carmagnole
oh yes you're rightMarquittamarr
This resolve option is not listed in their official documentation vitest.dev/config Where do you find it ? ^^Dobbin
I went to module sources lol, but I think it's here vitest.dev/config/#aliasMarquittamarr
It doesn't work. And it breaks half my existing unit tests.Prearrange
V
7

For SvelteKit users I ran into similar issue and had to add $lib to vitest.config.js

import { defineConfig } from 'vitest/config';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import path from 'path';

export default defineConfig({
  plugins: [svelte({ hot: !process.env.VITEST })],
  test: {
    globals: true,
    environment: 'jsdom',
  },
  resolve: {
    alias: {
      $lib: path.resolve(__dirname, './src/lib'),
    },
  },
});
Venator answered 9/11, 2022 at 12:32 Comment(0)
P
3

The final solution that worked for me was to include the test files in tsconfig.vitest.json:

tsconfig.app.json (unchanged from question post)

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": [
    "env.d.ts",
    "src/**/*",
    "src/**/*.vue"
  ],
  "exclude": [
    "vitest/**/*"
  ],
  "compilerOptions": {
    "composite": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    },
    "strict": true,
    "experimentalDecorators": true
  }
}

tsconfig.vitest.json

{
  "extends": "./tsconfig.app.json",
  "include": [
    "vitest/**/*",
  ],
  "exclude": [],
  "compilerOptions": {
    "composite": true,
    "lib": [],
    "types": [
      "node",
      "jsdom"
    ],
  }
}
Prearrange answered 25/1, 2023 at 16:10 Comment(1)
Yep, worked for me as well, like include=[...., "test"] in the regular tsconfing.app.jsonMural
D
3

Use vite-tsconfig-paths plugin.

https://vitest.dev/guide/common-errors#cannot-find-module-relative-path

Dramshop answered 21/12, 2023 at 7:6 Comment(0)
C
0

I found that all I needed to do was add the file web/tests/jsconfig.json, given that my Vue + Typescript + Vitest front-end is located in the "web" folder of my project.

// web/tests/jsconfig.json
// Helps VSCode detect typescript path aliases in test files
{
  "extends": "../tsconfig.json",
  "include": ["./**/*.test.ts"]
}

The missing include of the "tests/" folder seems to have been the primary issue, and the secondary issue was that VS Code couldn't detect the pathing. The actual tests worked with the default https://vitejs.dev/guide/#trying-vite-online -> https://vite.new/vue-ts config, so I thought it made more sense to use a jsconfig.json to update VS Code's awareness rather than muck with the general tsconfig.json

Casiecasilda answered 2/1 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.