Search code examples
vue.jsjestjsvue-clivue-test-utilsjest-webpack-alias

Vue Jest Aliases Configuration


I have an error when I want to run Jest because of moduleNameMapper settings.

I tried several methods, but nothing changes.

To reproduce:

  1. clone the repo: https://github.com/zoztorun/reproduce-webpack-alias-error
  2. npm install
  3. npm run test

terminal error ss


Solution

  • Since you're using Vue CLI, you should use @vue/cli-plugin-unit-jest, which can be added to your Vue CLI project with this command:

    vue add unit-jest
    

    This will also add a <rootDir>/test directory with a sample test, but that doesn't fit your project's test file pattern, which places *.spec.js adjacent to the source files.

    To adapt the result to your project:

    1. Delete <rootDir>/test (as it would be unused, and because it points to a nonexistent HelloWorld.vue)
    2. Edit the jest config in package.json to be:
    {
      "jest": {
        "preset": "@vue/cli-plugin-unit-jest",
        "testMatch": [
          "**/src/**/*.spec.[jt]s?(x)"
        ]
      }
    }
    
    1. Delete your test NPM script, since @vue/cli-plugin-unit-jest automatically adds its own test:unit script, which must be used instead (i.e., use npm run test:unit).