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

使用Vitest执行NestJS E2E测试时遇TypeError: __vite_ssr_import_1__不是函数

NestJS + Vitest E2E测试报错:TypeError: __vite_ssr_import_1__ is not a function

我在基于Vitest的NestJS项目中运行端到端(E2E)测试时遇到如下错误,折腾了好几个小时都没解决:

FAIL  test/app.e2e-spec.ts > AppController (e2e) > / (GET)
TypeError: __vite_ssr_import_1__ is not a function
 ❯ test/app.e2e-spec.ts:20:12

以下是我的Vitest配置文件和E2E测试文件,请帮忙排查问题:

vitest.config.e2e.ts

import swc from 'unplugin-swc';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    include: ['**/*.e2e-spec.ts'],
    globals: true,
    root: './',
  },
  resolve: {
    alias: {
      '@': __dirname + '/src',
      '@prismaClient': __dirname + '/prisma/client',
    },
  },
  plugins: [swc.vite()],
});

test/app.e2e-spec.ts

import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/module/app/app.module';


describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer()).get('/').expect(200).expect('Hello World!');
  });
});

问题排查与解决

这个错误是因为Vitest的SWC插件配置不完整,导致NestJS模块编译不符合Node.js运行环境要求,触发了SSR相关的导入异常。按以下步骤修改即可解决:

  1. 完善SWC的NestJS兼容配置
    修改vitest.config.e2e.ts,给swc插件添加Node.js环境适配和装饰器支持的配置:

    import swc from 'unplugin-swc';
    import { defineConfig } from 'vitest/config';
    
    export default defineConfig({
      test: {
        include: ['**/*.e2e-spec.ts'],
        globals: true,
        root: './',
        environment: 'node', // 明确指定测试环境为Node.js
      },
      resolve: {
        alias: {
          '@': __dirname + '/src',
          '@prismaClient': __dirname + '/prisma/client',
        },
      },
      plugins: [
        swc.vite({
          jsc: {
            target: 'es2021', // 匹配当前Node.js支持的语法版本
            transform: {
              decoratorMetadata: true, // NestJS依赖装饰器元数据
              legacyDecorator: true,
            },
          },
        }),
      ],
    });
    
  2. 校验依赖版本兼容性
    确保@nestjs/testing、vitest、unplugin-swc版本匹配:NestJS 10+建议搭配unplugin-swc@1.3.0+、vitest@0.30.0+。

  3. 确认导入路径正确性
    检查AppModule的导入路径../src/module/app/app.module是否存在拼写错误,确保文件实际位置与路径一致。

修改完成后重新运行测试,该导入错误即可消除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:30:10