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

Vitest无法加载meteor/meteor包的问题求助

Meteor + TypeScript + Vitest 导入错误问题

我创建了一个带有TypeScript的新Meteor项目,并安装了Vitest。但运行Vitest时出现以下错误:

FAIL  tests/main.test.ts [ tests/main.test.ts ]
Error: [vite-node] Failed to load meteor/meteor

测试代码如下:

import { Meteor } from 'meteor/meteor'
import { describe, test, expect } from 'vitest'

describe('replay', function () {
    test('package.json has correct name', async function () {
        const { name } = await import('../package.json')
        expect(name).toBe('replay')
    })

    if (Meteor.isClient) {
        test('client is not server', function () {
            expect(Meteor.isServer).toBe(false)
        })
    }

    if (Meteor.isServer) {
        test('server is not client', function () {
            expect(Meteor.isClient).toBe(false)
        })
    }
})

我不明白Vitest为何无法导入meteor,因为node_modules/@types/meteor已经提供了全局声明。


问题原因

Meteor的模块是框架内部特殊处理的,meteor/meteor并不是标准Node.js模块,Vitest(基于Vite)在Node环境下运行时无法识别这种特殊模块路径。而@types/meteor仅提供类型声明,不包含实际的模块实现代码,所以Vitest找不到可加载的模块文件。

解决方法

1. 配置Vitest的模块别名与模拟规则

在项目根目录创建vitest.config.ts,添加以下配置:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    mockReset: true,
    setupFiles: ['./tests/setup.ts'], // 可选,用于全局挂载模拟对象
  },
  resolve: {
    alias: {
      // 将meteor/meteor指向我们的模拟文件
      'meteor/meteor': './tests/mocks/meteor.ts',
    },
  },
})

2. 创建Meteor模块模拟文件

在tests/mocks/meteor.ts中编写模拟代码,提供测试所需的Meteor对象:

// 模拟Meteor核心对象,可根据测试需求扩展其他API
export const Meteor = {
  isClient: typeof window !== 'undefined',
  isServer: typeof window === 'undefined',
}

3. 可选:全局挂载Meteor对象(简化测试代码)

如果不想在每个测试文件中都导入Meteor,可以在tests/setup.ts中把模拟对象挂载到全局:

import { Meteor } from './mocks/meteor'

declare global {
  var Meteor: typeof Meteor
}

global.Meteor = Meteor

之后测试代码可以去掉import { Meteor } from 'meteor/meteor',直接使用全局的Meteor对象。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:09:14