DEV Community

Cover image for Configure Jest in Nuxt.js
Tincho
Tincho

Posted on

Configure Jest in Nuxt.js

If you already have a project created with Nuxt but without Jest configured, I'll show you how to do it.

💡 My Nuxt.js version is 2.14.12.

Steps

  1. Install dependencies

    npm i -D @vue/test-utils babel-core@^7.0.0-bridge.0 babel-jest jest vue-jest
    
  2. Add command test in package.json.

    {
      //...
      "scripts": {
        //...
        "test": "jest"
      }
      //...
    }
    
  3. Add file jest.config.js in root directory

    module.exports = {
      moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/$1',
        '^~/(.*)$': '<rootDir>/$1',
        '^vue$': 'vue/dist/vue.common.js',
      },
      moduleFileExtensions: ['js', 'vue', 'json'],
      transform: {
        '^.+\\.js$': 'babel-jest',
        '.*\\.(vue)$': 'vue-jest',
      },
      collectCoverage: true,
      collectCoverageFrom: [
        '<rootDir>/components/**/*.vue',
        '<rootDir>/pages/**/*.vue',
      ],
    }
    
  4. Add file .babelrc in root directory

    {
      "env": {
        "test": {
          "presets": [
            [
              "@babel/preset-env",
              {
                "targets": {
                  "node": "current"
                }
              }
            ]
          ]
        }
      }
    }
    
  5. Create test directory in root directory

    mkdir test
    
  6. Write your first test of your component /test/YourComponent.spec.js

    import { mount } from '@vue/test-utils'
    import YourComponent from '@/components/YourComponent'
    
    describe('YourComponent', () => {
      test('is a Vue instance', () => {
        const wrapper = mount(YourComponent)
        expect(wrapper.vm).toBeTruthy()
      })
    })
    

💡 I recommend you to read:

Thank you for readme! see you soon 😉

Latest comments (1)

Collapse
 
slidenerd profile image
slidenerd

if it isnt too much to ask could you add a more detailed example like how to test vuex actions getters mutations