Skip to content

Latest commit

 

History

History
103 lines (79 loc) · 3.73 KB

using-with-jest.md

File metadata and controls

103 lines (79 loc) · 3.73 KB

Using Vue Test Utils with Jest (recommended)

Jest is a test runner developed by Facebook, aiming to deliver a battery-included unit testing solution. You can learn more about Jest on its official documentation.

If you are using the Vue CLI to build your project, you can use the plugin cli-plugin-unit-jest to run Jest tests.

After setting up Jest, the first thing to do is to install Vue Test Utils and vue-jest to process Single-File Components:

$ npm install --save-dev @vue/test-utils vue-jest

Then, you need to tell Jest to transform .vue files using vue-jest. You can do so by adding the following configuration in package.json or in a standalone Jest config file:

{
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      // tell Jest to handle `*.vue` files
      "vue"
    ],
    "transform": {
      // process `*.vue` files with `vue-jest`
      ".*\\.(vue)$": "vue-jest"
    }
  }
}

Using with Babel

If you are going to use babel and import vue single file components with .vue extension inside your tests, you will need to install babel and transform .js files with babel-jest .

npm install --save-dev babel-jest @babel/core @babel/preset-env babel-core@^7.0.0-bridge.0

Then, you need to tell Jest to transform .js files using babel-jest. You can do so by adding the following configuration in package.json or in a standalone Jest config file:

{
  "jest": {
    "transform": {
      // process `*.js` files with `babel-jest`
      ".*\\.(js)$": "babel-jest"
    }
  }
}

Then you need to create babel config using babel.config.json or .babelrc.json config files:

{
  "presets": ["@babel/preset-env"]
}

You can also add these options to package.json:

{
  "babel": {
    "presets": ["@babel/preset-env"]
  }
}

Handling webpack aliases

If you use a resolve alias in the webpack config, e.g. aliasing @ to /src, you need to add a matching config for Jest as well, using the moduleNameMapper option:

{
  "jest": {
    // support the same @ -> src alias mapping in source code
    "moduleNameMapper": {
      "^@/(.*)$": "<rootDir>/src/$1"
    }
  }
}

Code Coverage

Jest can be used to generate coverage reports in multiple formats. The following is a simple example to get started with:

Extend your jest config with the collectCoverage option, and then add the collectCoverageFrom array to define the files for which coverage information should be collected.

{
  "jest": {
    "collectCoverage": true,
    "collectCoverageFrom": ["**/*.{js,vue}", "!**/node_modules/**"]
  }
}

This will enable coverage reports with the default coverage reporters. Further documentation can be found in the Jest configuration documentation, where you can find options for coverage thresholds, target output directories, etc.