Vitest Path Alias Configuration

This recipe shows how you can fix a common error when using TypeScript's paths configuration value to import modules in your application with aliases and importing modules in your tests. Vitest will not automatically know how to resolve the alias.

To fix this you must explicitly tell vitest how to resolve those aliases as well, you do so easily by adding a alias key in the Vitest config file.

Suppose this is your TypeScript config, i.e. tsconfig.json:

{
  "include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx"],
  "compilerOptions": {
	//...
    "paths": {
      "~/*": ["./app/*"]
    },
  }
}

In case we add modules from our project to our tests me must tell Vitest how to resolve this alias, i.e. ~

// @vite.config.ts
/// <reference types="vitest" />
import { defineConfig, configDefaults } from "vitest/config";
import path from "path";

export default defineConfig({
    test: {
        alias: {
			// * ↓
            "~": path.resolve(__dirname, "./app"),
        },
    },
});

Notice we resolve the path with Node's path module and __dirname variable which will print out the project's directory path.