wallabyjs / public

Repository for Wallaby.js questions and issues
http://wallabyjs.com
758 stars 45 forks source link

Vitest: ReferenceError: window is not defined #3091

Closed reitbauer closed 1 year ago

reitbauer commented 1 year ago

Issue description or question

In my project I use the window.localStorage. If I try to test this class I always get the error "ReferenceError: window is not defined" if I run the tests with the command "vitest --environment jsdom" all tests pass.

I have written a simple test for demo:

image

Wallaby diagnostics report

{
  editorVersion: '1.72.0',
  pluginVersion: '1.0.348',
  editorType: 'VSCode',
  osVersion: 'darwin 21.6.0',
  nodeVersion: 'v16.17.1',
  coreVersion: '1.0.1334',
  checksum: 'NmQ4OTI0NGM1NDZmMTNkZjk5ZDEwMGQ4NDk4NGUzMGIsMTY3ODQwNjQwMDAwMCww',
  config: {
    diagnostics: {
      vitest: {
        file: {
          config: "import { fileURLToPath, URL } from 'node:url';\n" +
            "import { resolve, dirname } from 'node:path';\n" +
            '\n' +
            "import { quasar, transformAssetUrls } from '@quasar/vite-plugin';\n" +
            "import vue from '@vitejs/plugin-vue';\n" +
            "import vueJsx from '@vitejs/plugin-vue-jsx';\n" +
            "import { defineConfig } from 'vite';\n" +
            "import vueI18n from '@intlify/vite-plugin-vue-i18n';\n" +
            '\n' +
            '// https://vitejs.dev/config/\n' +
            'export default defineConfig({\n' +
            '    plugins: [\n' +
            '        vue({ template: { transformAssetUrls } }),\n' +
            '        vueJsx(),\n' +
            '        quasar({\n' +
            "            sassVariables: 'src/styles/colors.scss',\n" +
            '        }),\n' +
            '        vueI18n({\n' +
            "            include: resolve(dirname(fileURLToPath(import.meta.url)), './src/locales/**'),\n" +
            '        }),\n' +
            '    ],\n' +
            '    resolve: {\n' +
            '        alias: {\n' +
            "            '@': fileURLToPath(new URL('./src', import.meta.url)),\n" +
            '        },\n' +
            '    },\n' +
            '});\n'
        },
        config: {
          allowOnly: true,
          watch: true,
          globals: false,
          environment: 'node',
          threads: true,
          clearMocks: false,
          restoreMocks: false,
          mockReset: false,
          include: [ '**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}' ],
          exclude: [ '**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**' ],
          testTimeout: 5000,
          hookTimeout: 10000,
          teardownTimeout: 1000,
          isolate: true,
          watchExclude: [ '**/node_modules/**', '**/dist/**' ],
          forceRerunTriggers: [ '**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**' ],
          update: false,
          reporters: [ 'default' ],
          silent: false,
          ui: false,
          uiBase: '/__vitest__/',
          open: true,
          css: { include: [], modules: { classNameStrategy: 'stable' } },
          coverage: {
            provider: 'c8',
            enabled: false,
            clean: true,
            cleanOnRerun: false,
            reportsDirectory: './coverage',
            excludeNodeModules: true,
            exclude: [
              'coverage/**',
              'dist/**',
              'packages/*/test{,s}/**',
              '**/*.d.ts',
              'cypress/**',
              'test{,s}/**',
              'test{,-*}.{js,cjs,mjs,ts,tsx,jsx}',
              '**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}',
              '**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}',
              '**/__tests__/**',
              '**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.{js,cjs,mjs,ts}',
              '**/.{eslint,mocha,prettier}rc.{js,cjs,yml}'
            ],
            reporter: [ 'text', 'html', 'clover', 'json' ],
            allowExternal: false,
            extension: [
              '.js',  '.cjs',
              '.mjs', '.ts',
              '.tsx', '.jsx',
              '.vue', '.svelte'
            ]
          },
          fakeTimers: { loopLimit: 10000, shouldClearNativeTimers: true, toFake: [ 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'setImmediate', 'clearImmediate', 'Date' ] },
          maxConcurrency: 5,
          dangerouslyIgnoreUnhandledErrors: false,
          defines: { __VUE_I18N_LEGACY_API__: false, __VUE_I18N_FULL_INSTALL__: true, __VUE_I18N_PROD_DEVTOOLS__: false },
          root: '<homeDir>/Development/SourceCode/RS/Frameworks/rs-framework-vue',
          mode: [],
          deps: { inline: [ {}, {}, {}, {}, {}, {}, '@nuxt/test-utils' ], registerNodeLoader: false },
          snapshotOptions: { snapshotFormat: {}, updateSnapshot: 'new' },
          setupFiles: [],
          cache: { dir: '<homeDir>/Development/SourceCode/RS/Frameworks/rs-framework-vue/node_modules/.vitest' },
          sequence: {},
          package: {
            version: '0.24.0',
            urls: { hooks: 'file://<homeDir>/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.348/wallabyf04c7c/runners/node/hooks.mjs' },
            paths: {
              root: '<homeDir>/Development/SourceCode/RS/Frameworks/rs-framework-vue/node_modules/vitest',
              dist: '<homeDir>/Development/SourceCode/RS/Frameworks/rs-framework-vue/node_modules/vitest/dist'
            }
          }
        }
      }
    },
    testFramework: { version: 'vitest@0.14.0', configurator: 'vitest@0.14.0', reporter: 'vitest@0.14.0', starter: 'vitest@0.14.0', autoDetected: true },
    preserveComments: false,
    extractComments: true,
    files: [
      { pattern: '**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', ignore: true, trigger: true, load: true, file: true },
      { pattern: '**/node_modules/**', ignore: true, trigger: true, load: true, file: true, test: true },
      { pattern: '**/dist/**', ignore: true, trigger: true, load: true, file: true, test: true },
      { pattern: '**/cypress/**', ignore: true, trigger: true, load: true, file: true, test: true },
      { pattern: '**/.{idea,git,cache,output,temp}/**', ignore: true, trigger: true, load: true, file: true, test: true },
      { pattern: '**/*.*', ignore: false, trigger: true, load: true, order: 1 }
    ],
    tests: [
      { pattern: '**/node_modules/**', ignore: true, trigger: true, load: true, test: true, file: false },
      { pattern: '**/dist/**', ignore: true, trigger: true, load: true, test: true, file: false },
      { pattern: '**/cypress/**', ignore: true, trigger: true, load: true, test: true, file: false },
      { pattern: '**/.{idea,git,cache,output,temp}/**', ignore: true, trigger: true, load: true, test: true, file: false },
      { pattern: '**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', ignore: false, trigger: true, load: true, test: true, order: 2 }
    ],
    workers: { initial: 1, regular: 1, recycle: false },
    filesWithNoCoverageCalculated: [],
    runAllTestsInAffectedTestFile: false,
    updateNoMoreThanOneSnapshotPerTestFileRun: false,
    compilers: {},
    logLimits: { inline: { depth: 5, elements: 5000 }, values: { default: { stringLength: 200 }, autoExpand: { elements: 5000, stringLength: 8192, depth: 10 } } },
    preprocessors: {},
    maxConsoleMessagesPerTest: 100,
    autoConsoleLog: true,
    delays: { run: 0, edit: 100, update: 0 },
    teardown: undefined,
    hints: {
      ignoreCoverage: '__REGEXP /ignore coverage|istanbul ignore/',
      ignoreCoverageForFile: '__REGEXP /ignore file coverage/',
      commentAutoLog: '?',
      testFileSelection: { include: '__REGEXP /file\\.only/', exclude: '__REGEXP /file\\.skip/' }
    },
    automaticTestFileSelection: true,
    runSelectedTestsOnly: false,
    mapConsoleMessagesStackTrace: false,
    extensions: {},
    env: {
      type: 'node',
      params: { runner: '--experimental-loader=file://<homeDir>/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.348/wallabyf04c7c/runners/node/hooks.mjs' },
      runner: '/usr/local/bin/node',
      viewportSize: { width: 800, height: 600 },
      options: { width: 800, height: 600 },
      bundle: true
    },
    reportUnhandledPromises: true,
    slowTestThreshold: 75,
    lowCoverageThreshold: 80,
    loose: undefined,
    symlinkNodeModules: undefined,
    configCode: 'auto.detect#1187933729'
  },
  packageJSON: {
    dependencies: {
      '@quasar/extras': '^1.15.4',
      axios: '^1.1.2',
      'device-uuid': '^1.0.4',
      'jwt-decode': '^3.1.2',
      moment: '^2.29.4',
      pinia: '^2.0.21',
      quasar: '^2.9.1',
      uuid: '^9.0.0',
      vue: '^3.2.38',
      'vue-i18n': '^9.2.2',
      'vue-router': '^4.1.5'
    },
    devDependencies: {
      '@intlify/vite-plugin-vue-i18n': '^6.0.3',
      '@quasar/vite-plugin': '^1.2.3',
      '@rushstack/eslint-patch': '^1.1.4',
      '@types/device-uuid': '^1.0.0',
      '@types/jsdom': '^20.0.0',
      '@types/node': '^16.11.56',
      '@types/uuid': '^8.3.4',
      '@vitejs/plugin-vue': '^3.0.3',
      '@vitejs/plugin-vue-jsx': '^2.0.1',
      '@vue/eslint-config-prettier': '^7.0.0',
      '@vue/eslint-config-typescript': '^11.0.0',
      '@vue/test-utils': '^2.0.2',
      '@vue/tsconfig': '^0.1.3',
      cypress: '^10.7.0',
      eslint: '^8.22.0',
      'eslint-plugin-cypress': '^2.12.1',
      'eslint-plugin-vue': '^9.3.0',
      jsdom: '^20.0.0',
      'npm-run-all': '^4.1.5',
      prettier: '^2.7.1',
      sass: '^1.32.12',
      'start-server-and-test': '^1.14.0',
      typescript: '~4.7.4',
      vite: '^3.0.9',
      vitest: '^0.24.0',
      'vue-tsc': '^0.40.13'
    }
  },
  fs: { numberOfFiles: 114 },
  debug: []
}
smcenlly commented 1 year ago

When Wallaby runs vitest it runs with the configuration set for your project. From what you said above, you're providing additional vitest overrides/otpions when you use the CLI.

Instead of running vitest CLI with the environment option, can you please update your configuration to set the environment? It should work for you.

vite.config.ts

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'jsdom',
    // other options...
  },
})