Skip to content

Vite resolve.alias causes some tests to fail #2063

Open
@rudolfbyker

Description

@rudolfbyker

Subject of the issue

It looks like vitest is not respecting the resolve.alias setting from the vite config file.

Steps to reproduce

See https://github.com/rudolfbyker/vitest-vue2-vuetify-repro

Expected behaviour

The test should pass.

Actual behaviour

"Cannot read properties of undefined" whenever we try to access something like "$vuetify" on a Vue instance.

Possible Solution

No solutions, but some workarounds:

Workaround 1: Monkey-one of my colleagues found a workaround. However, it's a bit arduous when there are many tests:patch the require function in tests (yuck)

  1. Use alias vue: "vue/dist/vue.common.js" instead of vue: "vue/dist/vue.esm.js".
  2. Create a utility function
export function forceVueAlias(overwrite: string) {
  // Load global module.
  const globalModule = require('module');
  // Save original require method.
  const _require = globalModule.prototype.require;

  globalModule.prototype.require = function () {
    if (arguments["0"] === "vue") arguments["0"] = overwrite;

    // Return result from original function.g
    return _require.apply(this, arguments);
  };
}
  1. Use it at the top of every test:
forceVueAlias("vue/dist/vue.common.js");

Workaround 2:

Don't use aliases. But then I can't have the runtime compiler for my project, which is a big problem.

Workaround 3:

import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), "");

  return {
    resolve: {
      alias: {
        // This enables the runtime compiler for Vue 2.
        vue: "vue/dist/vue.esm.js",
      },
    },
    
    test: {
      alias: {
        // Disable the runtime compiler during tests.
        vue: "vue",
      },
    },
  };
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions