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

Vitest中ReferenceError: File Is Not Defined的原因及解决方法

Vitest中使用File对象抛出ReferenceError: File Is Not Defined的原因及解决方法

问题描述

日常业务代码中可正常使用File对象,但在Vitest测试中调用new File()时,抛出如下错误:

ReferenceError: File is not defined
 ❯ test/basic.test.ts:25:23
     23| 
     24| test('File', () => {
     25|   let applicationZip = new File(new Array<Blob>(), "Mock.zip", { type: 'application/zip' })
       |                       ^
     26| })
     27| 

我的vite.config.ts配置:

/// <reference types="vitest" />
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// Configure Vitest (https://vitest.dev/config/)
export default defineConfig({
  test: {
    /* for example, use global to avoid globals imports (describe, test, expect): */
    // globals: true,
  },
  plugins: [vue()],
})

测试文件代码:

import { assert, expect, test } from 'vitest'

test('File', () => {
  let applicationZip = new File(new Array<Blob>(), "Mock.zip", { type: 'application/zip' })
})

原因分析

Vitest默认运行在Node.js环境中,而File是浏览器环境专属的Web API,Node.js标准库并未内置该对象,因此在测试中直接调用会触发未定义错误。

解决方法

方法一:切换Vitest到浏览器模拟环境(jsdom)

Vitest支持通过配置environment参数启用jsdom,jsdom会模拟完整的浏览器DOM环境,自动提供File、Blob等浏览器API。

修改vite.config.ts的test配置:

/// <reference types="vitest" />
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  test: {
    // 启用jsdom模拟浏览器环境
    environment: 'jsdom',
    // 若需要全局使用test/expect等方法,可取消注释下面一行
    // globals: true,
  },
  plugins: [vue()],
})

方法二:手动模拟File对象(无需切换环境)

如果仅需在个别测试中使用File,不想切换整个测试环境,可以手动在测试文件中模拟File的实现:

// 在测试文件顶部添加File对象模拟
global.File = class File extends Blob {
  constructor(blobParts: BlobPart[], fileName: string, options?: FilePropertyBag) {
    super(blobParts, options);
    this.name = fileName;
    this.lastModified = options?.lastModified || Date.now();
  }
  name: string;
  lastModified: number;
}

import { assert, expect, test } from 'vitest'

test('File', () => {
  let applicationZip = new File([], "Mock.zip", { type: 'application/zip' })
  // 可添加断言验证模拟是否生效
  expect(applicationZip.name).toBe('Mock.zip')
})

适用场景

  • 方法一适合需要用到大量浏览器API的测试场景(如DOM操作、Blob/File处理等),配置一次即可全局生效。
  • 方法二适合仅需临时使用File对象的简单测试,无需修改全局测试环境配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:35:20