Nuxt.JS Development Tools

From WikiOD

Testing is an indispensable part of the web application development process. Nuxt.js tries to help you simplify this part of the work.

End-to-end testing[edit | edit source]

Ava  is a very powerful JavaScript testing framework, combined with  jsdom , we can easily test nuxt applications end-to-end.

First, we need to add ava and jsdom as the development dependencies of the project:

npm install --save-dev ava jsdom

Then add a test script to package.json and configure ava to compile the file to be tested:

package.json

"scripts": {
   "test": "ava",
 },
 "ava": {
   "require": [
     "babel-register"
   ]
 },
 "babel": {
   "presets": [
     "es2015"
   ]
 }

Next, we can write the logic code of the unit test in the test directory:

mkdir test

Suppose we have such a page pages/index.vue:

<template>
 <nowiki> </nowiki> <nowiki><h1 class="red">Hello {{ name }}</nowiki>!<nowiki></h1></nowiki>
 </template>
 
 <nowiki><script>
 export default {
   data () {
     return { name: 'world' }
   }
 }
 </script></nowiki>
 
 <nowiki><style>
 .red {
   color: red;
 }
 </style></nowiki>

When we use npm run dev to start the development server and open http://localhost:3000 with a browser  , we can see the red Hello world title.

Add a unit test file test/index.test.js:

import { resolve } from 'path'
 import test from 'ava'
 import { Nuxt, Builder } from 'nuxt'
 
 // We use a variable retention nuxt with serverInstance reference// So you can turn them off after the unit tests are over
 let nuxt = null
 
 // initialization Nuxt.js And create a listener localhost:4000Server
 test.before('Init Nuxt.js', async (t) => {
   const rootDir = resolve(__dirname, '..')
   let config = {}
   try { config = require(resolve(rootDir, 'nuxt.config.js')) } catch (e) {}
   config.rootDir = rootDir // Project directory
   config.dev = false // Production build mode
   nuxt = new Nuxt(config)
   await new Builder(nuxt).build()
   nuxt.listen(4000, 'localhost')
 })
 
 //  Test generatedhtml
 test('routing / Effective and renderable HTML', async (t) => {
   const context = {}
   const { html } = await nuxt.renderRoute('/', context)
   t.true(html.includes('<nowiki><h1 class="red">Hello world!</h1></nowiki>'))
 })
 
 //Test the effectiveness of elements
 test('routing / Valid and rendered HTML has specific CSS styles', async (t) => {
   const window = await nuxt.renderAndGetWindow('<nowiki>http://localhost:4000/'</nowiki>)
   const element = window.document.querySelector('.red')
   t.not(element, null)
   t.is(element.textContent, 'Hello world!')
   t.is(element.className, 'red')
   t.is(window.getComputedStyle(element).color, 'red')
 })
 
 //Shut down the server and Nuxt instance, stop file monitoring。
 test.after('Closing server and nuxt.js', (t) => {
   nuxt.close()
 })

Run the above unit test:

npm test

In fact, jsdom is somewhat restrictive, because it does not use any browser engine behind it, but it can also cover most of the tests on dom elements. If you want to use a real browser engine to test your application, it is recommended to take a look at  Nightwatch.js .

ESLint[edit | edit source]

ESLint is a great tool that helps us improve the specification and quality of our code.

Integrating  ESLint in Nuxt.js  is very simple. First, we need to install a series of dependency packages of ESLint:

npm install --save-dev babel-eslint eslint eslint-config-standard eslint-plugin-html eslint-plugin-promise eslint-plugin-standard eslint-plugin-import eslint-plugin-node

Then, create a .eslintrc.js file in the project root directory to configure ESLint:

module.exports = {
   root: true,
   env: {
     browser: true,
     node: true
   },
   parserOptions: {
     parser: 'babel-eslint'
   },
   extends: [
     'eslint:recommended',
     // <nowiki>https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention</nowiki>
     // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
     'plugin:vue/recommended',
     'plugin:prettier/recommended'
   ],
   //check .vuedocument
   plugins: [
     'vue'
   ],
   //Custom rule
   rules: {
     'semi': [2, 'never'],
     'no-console': 'off',
     'vue/max-attributes-per-line': 'off',
     'prettier/prettier': ['error', { 'semi': false }]
   }
 }

Finally, we add a lint and lintfix script command to the package.json file:

"scripts": {
   "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
   "lintfix": "eslint --fix --ext .js,.vue --ignore-path .gitignore ."
 }

You can now start lint to check for errors:

npm run lint

Or lintfix can also fix those repairable

npm run lintfix

ESLint will check all JavaScript and Vue files, and ignore the ignored files defined in .gitignore.

It is also recommended to enable ESLint hot update mode through webpack. In this way, ESLint will be saved when npm run dev. Just add the following to your nuxt.config.js:

...
   /*
    ** Build configuration
   */
   build: {
    /*
     **You can expand herewebpackConfiguration
    */
    extend(config, ctx) {
       // Run ESLint on save
       if (ctx.isDev && ctx.isClient) {
         config.module.rules.push({
           enforce: "pre",
           test: /\.(js|vue)$/,
           loader: "eslint-loader",
           exclude: /(node_modules)/
         })
       }
     }
   }

A best practice is to add "precommit": "npm run lint" to package.json, so that the code can be checked and verified automatically before each code submission.