DEV Community

Mike Healy
Mike Healy

Posted on • Updated on

Running Jest with a Vue2 application

The Vue CLI and test utils have a 'happy path' to setup testing libraries, but they are naturally geared to the latest version of Vue and other dependencies.

If you need to add tests to an existing Vue 2 application you might find the process a little tricky.

You'll need to install the version of Vue test utils and vue-jest that correspond to your version of Vue.

For example if you're running Jest 29, you'll need to install vue2-test like so:

npm install --save-dev @vue/test-utils@1 @vue/vue2-jest@29
Enter fullscreen mode Exit fullscreen mode

Because the tests run in an environment without a native DOM we'll also need to configure them to use the jsdom implementation.

Install the package like so:

npm install --save-dev jest-environment-jsdom
Enter fullscreen mode Exit fullscreen mode

Then configure Jest to use the virtual JS DOM. Jest can be configured either via a dedicated file, or through your package.json like so:

{
 // other config...

 "jest": {
        "testEnvironment": "jsdom",
        "moduleFileExtensions": [
            "js",
            "json",
            "vue"
        ],
        "setupFiles": [
            "./jest-setup.js"
        ],
        "transform": {
            "^[^.]+.vue$": "@vue/vue2-jest",
            ".*\\.(js)$": "babel-jest"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In my case I required some extra config that's loaded in jest-setup.js. This is because my app had global dependencies for LoDash and a utilities file. To make these functions available in the test environment they are loaded like this.

jest-setup.js

import lodash from 'lodash';
import utils from './resources/js/utils.js';

global._ = lodash;
global.utils = utils;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)