jest ReferenceError: Vue is not defined

6.3k Views Asked by At

We are introducing Jest to an existing project.

However, I wrote an example test code. The above error occurred.

   ReferenceError: Vue is not defined

      1 | import User from "../components/modal/ad/AdAdd";
    > 2 | import { mount } from "@vue/test-utils";
        | ^
      3 |
      4 | describe("user component", () => {
      5 |   let wrapper;

How can I solve this??

//User.test.js

import User from "../components/modal/ad/AdAdd";
import { mount } from "@vue/test-utils";

describe("user component", () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(User);
  });
  test("render", () => {
    expect(wrapper.vm.oSid).toBe(0);
  });
});
export default {
  data() {
    return {
      Sid: 0,
      deleteList: [],
    };
  },
//package.json
"dependencies": {
    "eslint-plugin-jest": "^26.2.2",
    "vue": "^2.6.11",
    "vuetify": "^2.4.0",
    "vuex": "^3.4.0",
  },
  "devDependencies": {
    "@babel/core": "^7.18.0",
    "@babel/preset-env": "^7.18.0",
    "@types/jest": "^27.5.1",
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-service": "^3.0.5",
    "@vue/eslint-config-prettier": "^6.0.0",
    "@vue/test-utils": "^2.0.0",
    "babel-core": "^7.0.0-bridge.0",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^28.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-vue": "^6.2.2",
    "jest": "^28.1.0",
    "jest-environment-jsdom": "^28.1.0",
    "speed-measure-webpack-plugin": "^1.5.0",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "vue-cli-plugin-vuetify": "~2.4.0",
    "vue-jest": "^3.0.7",
    "vue-template-compiler": "^2.6.11",
    "vuetify-loader": "^1.7.0"
  }

I just mounted it, but it says the view is undefined. I don't know how to solve it.

What's wrong??

I haven't been able to solve the above error for several days.

I want to solve it. Any help would be appreciated.

2

There are 2 best solutions below

1
On

You are using Vue version 2 with @vue/test-utils 2.0.0 which is for Vue version 3.

You can find the correct @vue/test-utils version for Vue 2 here

3
On

I had the same error with vue3 and jest v.28, what solved it was to add

    testEnvironmentOptions: {
       customExportConditions: ["node", "node-addons"],
    },

into jest.config.js. This overrides versions of the library loaded from exports in package.json as explained in jest config page. As it defaults to ['browser'] for jest-environment-jsdom, and my failing tests were all that targeted the UI, presumably the right libraries were not imported for the jsdom environment.

Alternatively, if you want a solution that doesn't affect other imports, add this to jest.config.js instead:

moduleNameMapper: {
  "^@vue/test-utils": "<rootDir>/node_modules/@vue/test-utils/dist/vue-test-utils.cjs.js"
}

This will tell Jest to import the 'node' version of @vue/test-utils without impacting other imports.