Home

Awesome

vue-test-utils-jest-example

Example project with .vue files, using vue-test-utils and Jest to run unit tests.

Just Want to Get Started?

git clone https://github.com/hchiam/vue-test-utils-jest-example.git
cd vue-test-utils-jest-example
npm install
npm t

This project is based on the vue-cli webpack-simple template. Test-specific changes include:

Additional Dependencies

Additional Configuration

package.json

The following configurations are recommended for Jest:

{
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      // tell Jest to handle *.vue files
      "vue"
    ],
    "transform": {
      // process js with babel-jest
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
      // process *.vue files with vue-jest
      ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
    },
    // support the same @ -> src alias mapping in source code
    "moduleNameMapper": {
      "^@/(.*)$": "<rootDir>/src/$1"
    },
    // serializer for snapshots
    "snapshotSerializers": [
      "<rootDir>/node_modules/jest-serializer-vue"
    ],
    "mapCoverage": true
  }
}

.babelrc

Our default Babel config disables ES modules transpilation because webpack already knows how to handle ES modules. However, we do need to enable it for our tests because Jest tests are run directly in Node.

Also, if our tests are run in a relatively newer version of Node, most of the ES features are already supported - we can tell babel-preset-env to target the Node version we are using. This skips transpiling unnecessary features and makes our tests boot faster.

To apply these options only for tests, we need to add a separate config under env.test (this will be automatically picked up by babel-jest):

{
  "presets": [
    ["env", { "modules": false }]
  ],
  "env": {
    "test": {
      "presets": [
        ["env", { "targets": { "node": 8 }}]
      ]
    }
  }
}

Build Commands

# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run build

# run tests
npm test

For detailed explanation on how things work, consult the docs for vue-test-utils.