typescriptvitevitest

Vitest defineConfig, 'test' does not exist in type 'UserConfigExport'


Trying to setup vitest on an already existing vite (vue 3, typescript) project.

My vite.config.ts looks like this:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
  },
  plugins: [vue()],
});

But in VS code it complains:

vscode red lines under test prop

On hover I see:

Argument of type '{ test: { globals: boolean; environment: string; }; plugins: Plugin[]; }' is not assignable to parameter of type 'UserConfigExport'. Object literal may only specify known properties, and 'test' does not exist in type 'UserConfigExport'.ts(2345)

I can make it go away if I change this line:

import { defineConfig } from 'vite';

To:

import { defineConfig } from 'vitest/config';

But why? What's up with this? Why should I have to import defineConfig from vitest in order to get it to support the test property?


Solution

  • Short answer:

    Because this is how TypeScript works. Vite config interface does not know anything about Vitest and TS does not allow excessive properties (properties not defined by the type/interface)


    Because Vite itself does not know anything about Vitest and it's configuration. So Vitest must extend Vite config (defined as TS interface)

    In order to use this extended interface (instead of the original one), you must first import it.

    So instead of doing this (importing pure Vite config):

    import { defineConfig } from 'vite';
    

    do this (importing Vite config extended by Vitest):

    import { defineConfig } from 'vitest/config';
    

    Alternatively you can also use a "tripple slash command" as documented in Configuring Vitest

    /// <reference types="vitest" />
    import { defineConfig } from 'vite'
    
    export default defineConfig({
      test: {
        // ...
      },
    })