3

I'm integrating vitest with a NextJS13 app, but running into problems with a simple test run.

vitest run error

Not sure what the problem is, I tried to do some tweaking with the vitest.config.ts but no luck. I tried adding the dir option, modified the include option to grab files from the source file but no luck.

I thought maybe it had to do with the tsconfig.json file, but it's still outputting the error.

This is the directory of the file

src directory

Here are the files in question:

vitest.config.ts

/// <reference types="vitest" />

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
    setupFiles: 'setupTests.ts',
    // dir: './src'
    // includeSource: ['src/**/*.{js,ts,tsx}'],
  },
});

tsconfig.json

{
"compilerOptions": {
    "target": "ES2017",
    "lib": ["es6", "dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "ESNEXT",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "incremental": true,
    // "paths": {
    //     "src": ["./src/*"]
    // }
},
"exclude": ["node_modules"],
"include": ["vitest.config.ts","**/*.ts", "**/*.tsx", "next-env.d.ts", 
"next.config.js"]
}

DataTable.test.tsx - src/common/components/DataTable/DataTable.test.tsx

// components

import DataTable from 'src/common/components/DataTable';

// dependencies
import {describe, it} from 'vitest'
import {screen, render} from '@testing-library/react'

describe('DataTable test', () => {

    it('render the app', () => {
        // arrange
            render(<DataTable />)
        // act
            const assetText = screen.getByText("asset")
        // assert
            // expect(assetText).toBeInTheDocument()
    })
})

DataTable component - src/common/components/DataTable/DataTable.tsx

export const DataTable = () => {

    return (
        <div>
            <h1>assets</h1>
        </div>
    );
};

Index.tsx - src/common/components/DataTable/index.tsx

import { DataTable } from 'src/common/components/DataTable/DataTable';

export default DataTable;

I'm new to vitest and nextjs, your help/guidance will be appreciated.

medev21
  • 2,469
  • 8
  • 31
  • 43
  • That's because tsc has failed to find the file that matches the path: it appears to be a custom alias than an actual physical path. What happens when you uncomment the `path` config in your tsconfig? – Terry Feb 08 '23 at 00:25
  • @Terry still the same error, I've added that thinking it will help find the src folder, but it's not helping, so I commented it. – medev21 Feb 08 '23 at 00:44
  • If `DataTable.test.tsx` is in the same directory as `DataTable.tsx`, why not just import it as `import DataTable from './DataTable';`? Otherwise, if you're going to use the paths compiler option in tsconfig.json to get to the root src, you would also need to specify it as `"src/*": ["./src/*"]` to get its subdirectories. – M. Desjardins Feb 08 '23 at 14:11
  • @M.Desjardins yea that will solve the problem, but I would like keep it as absolute import path. What if the test needs to import files outside its parent directory, in that case you'll end up with this `../../../`. I have tried the path option in the `tsconfig` file but it's not working either; see the commented line in my `tsconfig` file – medev21 Feb 08 '23 at 17:50
  • @medev21 That's fair. The paths option in tsconfig should work, but what you have in your tsconfig—`"src": ["./src/*"]`—would only map "src" imports, but not "src/common/components/DataTable". In order to match anything under the "src" directory, you would need to use "src/*" as the key in the paths option, like so: `"src/*": ["./src/*"]` – M. Desjardins Feb 08 '23 at 18:51
  • @M.Desjardins yea I tried that in the path option, `"src/*": ["./src/*"]`, but for some reason I'm still getting an error. I mean I feel like it should work but not I'm sure why, I'm suspecting there is a missing config in vitest but don't know where exactly; first time working with i, I usually work with jest. This is for education purposes – medev21 Feb 08 '23 at 19:15
  • In this project, i didn't use the create-next-app command, i just manually imported dependencies, perhaps I'm missing a dependency somewhere. I'm just speculating here – medev21 Feb 08 '23 at 19:16
  • 1
    I wasn't using any templates either, just manually adding what I needed to my test workspace. But I did forget one thing, and that is a plugin like [vite-tsconfig-paths](https://www.npmjs.com/package/vite-tsconfig-paths) (or otherwise manually configuring the module aliases). See [Absolute path not working in Vite project React TS](https://stackoverflow.com/a/68250175/1507350) for more information. – M. Desjardins Feb 08 '23 at 19:33
  • Ah, so I was missing a config/dependency. Thanks for looking into this. I gave it a point to your response. – medev21 Feb 08 '23 at 20:58

1 Answers1

4

There are two things needed here to make the import DataTable from 'src/common/components/DataTable'; import work:

  1. TypeScript needs the paths compilerOption set.
  2. Vite needs to have the same alias set.

The "paths" compilerOption in TypeScript will need a /* on the end of the "src" key to be able to resolve paths underneath the "src" directory (see tsconfig.json reference):

{
  "compilerOptions": {
    "paths": {
      "src/*": ["./src/*"]
    }
  }
}

Vite/Vitest will also need to know how to resolve "src/common/components/DataTable", and that would usually be done with the resolve.alias setting, but rather than duplicating the alias here, you could also use a plugin, like vite-tsconfig-paths, to add the path aliases if finds in relevant tsconfig.json files:

import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default {
  plugins: [tsconfigPaths(), react()],
};
M. Desjardins
  • 605
  • 3
  • 13
  • This fixed the issue for me. In NextJs 13.4, the paths field in tsconfig.json is already set. So, adding, tsconfigPaths to the plugin fixed it. Thank you M. – Justice May 07 '23 at 14:21