DEV Community

Cover image for Configure Jest in Nuxt.js
Tincho
Tincho

Posted on

6 1

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 😉

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top 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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay