我有一个包含此导入的测试文件: import { useGlobalStore } from "@stores"

路径为src/stores

这在项目中工作正常,但在测试时,我收到以下错误: Error: Failed to resolve import "@stores" from "src/components/Footer/__test__/Footer.test.tsx". Does the file exist?

在之前使用Jest时,我使用modeNameMapper修复了它:

  moduleNameMapper: {
    "^stores/(.*)$": "<rootDir>/src/stores/$1",
  },

我try 根据文档将其添加到Vitest配置中,但没有结果. 这是我的配置文件:

export default defineConfig({
  test: {
    resolve: {
      // ...rest of the code ...
      alias: {
        // I tried all the commented lines without success

        // '@': path.resolve(__dirname, './src'),
        // '@': './src',
        // '@stores': './src/stores', 
        // '@/stores': new URL('./src/stores', import.meta.url).pathname, 

        '@/': new URL('./src/', import.meta.url).pathname, 
      },
    },
  },
});

我试了很多东西,但都没有成功.

推荐答案

正如VITEST文档所解释的,如果项目依赖于tsconfig.json中的baseUrl,则VTE在默认情况下不会考虑tsconfig.json.

最实用的解决方案是安装vite-tsconfig-paths并修改vitest.config.js,如下所示:

// install and import tsconfigPaths
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({

  //add tsconfigPaths() below
  plugins: [tsconfigPaths()],

  test: {
    // rest of the code
  },
});

Typescript相关问答推荐

Angular -使用Phone Directive将值粘贴到控件以格式化值时验证器不工作

找不到带名称的管道''

使用ngrok解析Angular 时出现HTTP故障

如何缩小变量访问的对象属性范围?

带占位符的模板文字类型何时扩展另一个?

使用`renderToPipeableStream`时如何正确恢复服务器端Apollo缓存?

使用2个泛型类型参数透明地处理函数中的联合类型

使用Dockerfile运行Vite React应用程序时访问env变量

从TypeScrip中的其他类型检索泛型类型

如何在react组件中使用doctype和html标签?

为什么&;(交集)运算符会删除不相交的属性?

无法将从服务器接收的JSON对象转换为所需的类型,因此可以分析数据

VITEST警告:当前的测试运行器不支持After Each/teardown挂钩

顶点堆叠的图表条形图未在正确的x轴上显示

如何使函数参数数组不相交?

如何以类型安全的方式指定键的常量列表,并从该列表派生所挑选的接口?

是否使用类型将方法动态添加到类?

带有过滤键的 Typescript 映射类型

包含多个不同类构造函数的接口的正确类型?

是否可以从 TypeScript 的类型推断中排除this?