Michael Miller
Michael Miller

Reputation: 225

Vitest - ReferenceError: File Is Not Defined

I'm usually able to use File wherever I want to in my code, but for some reason when I try using it in vitest it throws this error. Why does this happen and how can I resolve this error?

Here is my 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()],
})

And here is my test file code.

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

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

Whenever I run vitest it throws the following error.

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| 

Upvotes: 4

Views: 5870

Answers (1)

Michael Miller
Michael Miller

Reputation: 225

I discovered through here that File isn't in nodejs but instead provided by the browser's DOM, thus explains the error from vitest since it's pure node. Through some more thorough reading of vitest's docs I learned that vitest can be configured with an environment like jsdom which will provide the File object I need in my test. After modifying my vite.config.ts with the following environment setting that error no longer showed up.

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

export default defineConfig({
  plugins: [vue()],
  test: {
    globals: true,
    environment: "jsdom",
  },
  root: ".",
})

Upvotes: 4

Related Questions