Vitest - @ src folder alias not resolved in test files

Viewed 1600

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}'],
  },
});
1 Answers

You just have to specify the aliases in you're 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, '.')
    },
  },
}

Related