You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Vue3+Jest测试中[@vue/compiler-sfc]未提供fs选项的错误?

解决[@vue/compiler-sfc] No fs option provided 测试错误

问题本质

这个错误是Vue的SFC编译器在Jest测试环境中解析第三方库的类型导入时,缺少文件系统访问权限配置导致的——Jest的测试环境并非标准Node环境,编译器无法读取第三方库的类型文件。

可行解决方案

1. 给vue-jest配置fs选项

在jest.config.js的transform配置中,手动传入Node的fs模块给vue-jest:

module.exports = {
  transform: {
    '^.+\\.vue$': ['vue-jest', {
      compilerOptions: {
        fs: require('fs')
      }
    }]
  },
  // 保留你原有的其他配置
}

直接给编译器提供文件系统访问能力,让它能正常解析第三方类型文件。

2. 优化TypeScript类型导入语法

用TypeScript 4.5+支持的type-only import语法,明确标记这只是类型导入,避免测试环境的运行时解析问题:

<script setup lang="ts">
// 两种写法都可以,推荐第二种更明确的语法
import type { Props as SelectProps } from '@library/design-system-core/dist/components/molecule/Select'
// import { type Props as SelectProps } from '@library/design-system-core/dist/components/molecule/Select'
</script>

3. 升级适配Vue3.3的vue-jest版本

如果你的vue-jest版本偏老,对Vue3.3的SFC编译支持不完善,换成Vue3专用的@vue/vue3-jest并升级到最新兼容版本:

npm install @vue/vue3-jest@latest --save-dev

注意版本匹配:jest 29.x对应@vue/vue3-jest 29.x,jest 28.x对应28.x版本。

4. 彻底mock第三方类型模块

如果测试不需要验证第三方类型,直接mock整个类型模块:

  • 在测试文件顶部添加mock:
jest.mock('@library/design-system-core/dist/components/molecule/Select', () => ({
  Props: {}
}))
  • 或者在jest.config.js中配置全局mock:
module.exports = {
  moduleNameMapper: {
    '^@library/design-system-core/dist/components/molecule/Select$': '<rootDir>/__mocks__/SelectTypeMock.ts'
  }
}

然后在__mocks__/SelectTypeMock.ts中导出空的类型结构:

export interface Props {}

尝试顺序建议

优先试方案2(改动最小),无效再试方案1或3(配置/依赖升级),最后考虑方案4(彻底隔离)。

内容的提问来源于stack exchange,提问作者Mona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:43:34