next.jsreact-testing-libraryvitest

import not understood by test, resolve error thrown


When I run the test getting the error as:

Error: Failed to resolve import "@/components/card/LoadingCards" from "app/page.tsx". Does the file exist?
  Plugin: vite:import-analysis
  File: /Users/mohamedarif/Documents/Tranings/NextJS/home-away/app/page.tsx:1:25
  1  |  import { jsxDEV } from "react/jsx-dev-runtime";
  2  |  import LoadingCards from "@/components/card/LoadingCards";
     |                            ^
  3  |  import CategoriesList from "@/components/home/CategoriesList";
  4  |  import PropertiesContainer from "@/components/home/PropertiesContainer";

Here is my page.tsx:

import LoadingCards from '@/components/card/LoadingCards';
import CategoriesList from '@/components/home/CategoriesList';
import PropertiesContainer from '@/components/home/PropertiesContainer';
import { Suspense } from 'react';

export default function HomePage({
  searchParams,
}: {
  searchParams: { category?: string; search?: string };
}): JSX.Element {
  return (
    <section>
      <h1>Welcome</h1>
      <CategoriesList category={searchParams.category} search={searchParams.search} />
      <Suspense fallback={<LoadingCards />}>
        <PropertiesContainer category={searchParams.category} search={searchParams.search} />
      </Suspense>
    </section>
  );
}

I am using Next.js with Vitest and React Testing Library. How to solve the alias issue?


Solution

  • I updated the vitest config. it works fine now.

    import react from '@vitejs/plugin-react';
    import path from 'path';
    import { defineConfig } from 'vitest/config';
    
    export default defineConfig({
      plugins: [react()],
      test: { environment: 'jsdom' },
      resolve: {
        alias: {
          '@': path.resolve(__dirname),
        },
      },
    });