Automated Testing with Node.js for Beginners

Subscribe to my newsletter and never miss my upcoming articles

Why Test?

Testing your code is an essential phase of web development. It keeps your code from running into errors and ensures that it works across all devices and browsers. But it can be time-consuming and complicated to test your code, especially if you are a beginner.

Some common testing such as linting and minifying can be automated, helping you to fix common bugs and flag errors in your code more easily than ever. This helps to save you lots of time when performing tests!

Linting: process of running a program that will analyse code for potential errors. - Wikipedia

Minifying: process of removing all unnecessary characters from the source code of interpreted programming languages or markup languages without changing its functionality. - Wikipedia

In this tutorial, I will show you how to set up a task runner with Node.js and npm to automate 3 processes:

  1. HTML Linting and Minifying: fix errors and bad formatting
  2. CSS Autoprefixing and Linting: add prefixes to run in older browsers and fix errors
  3. JavaScript Linting and Transpiling: fix errors and transpile new JS code to work in older browsers

Step 1: Download Node.js and npm

Download Node.js (with npm) at: https://nodejs.org/en/download/

After it is installed, to check if it is there, go to your command prompt:

node -v
npm -v

Step 2: Install Gulp

Gulp is an automated toolkit we will be using to create our task runner for testing (see documentation). You can install it via npm by running this line on your command prompt:

npm install --global gulp-cli

Step 3: Create a project, navigate to it and initialize npm

mkdir test-project
cd test-project
npm init

After initializing npm, a package.json will be generated in your project directory.

Step 4: Set up Gulp as a dependency

npm install --save-dev gulp

You should now see gulp in your package.json under the devDependencies property.

Step 5: Create gulpfile.js

In your project directory, create a gulpfile.js file, where we will be writing our task runner in and add the following as the first line:

const gulp = require('gulp');

Now, let's create the 3 automated test tasks start from html, css and then javascript.

Step 6: Create 'html' task

Let's start with creating the html task with gulp-htmltidy, a gulp plugin for HTML linting. See documentation.

First, we install it with:

npm install --save-dev gulp-htmltidy

Then, add the dependency in the gulpfile.js:

const htmltidy = require('gulp-htmltidy');

Add the following test below to check for errors in your html files:

gulp.task('html', function() {
  return gulp.src('./*.html') // your html directory
        .pipe(htmltidy())
        .pipe(gulp.dest('build/')); //writes the output, cleanly formatted HTML to the build directory
});

Great! we have created our first test to check for errors and poor formatting in HTML. Let's move on to creating a CSS test.

Step 7: Create 'css' task

Install gulp-autoprefixer (documentation) and gulp-csslint (documentation) by running:

npm install --save-dev gulp-autoprefixer
npm install --save-dev gulp-csslint

Then, just like for htmltidy, we add the dependencies at the top of gulpfile.js:

const autoprefixer = require('gulp-autoprefixer');
const csslint = require('gulp-csslint');

Finally, we add the css task below the html task like so:

gulp.task('css', function() {
    return gulp.src('./*.css') //your css directory
        .pipe(csslint())
        .pipe(csslint.formatter())
        .pipe(autoprefixer({
            browsers: ['last 5 versions'],  //config to add prefixes to work on older browsers
            cascade: false
        }))
        .pipe(gulp.dest('./build'));
});

Now, we have our css test task ready to go! Let's do the last one for our javascript code.

Step 8: Create 'js' task

For javascript testing, we will install gulp-jshint (documentation) and gulp-babel (documentation) by running:

npm install --save-dev gulp-babel @babel/preset-env
npm install --save-dev @babel/core
npm install --save-dev jshint gulp-jshint

Then, for the last time, add the dependencies:

const babel = require('gulp-babel');
const jshint = require('gulp-jshint');

And the task at the bottom of gulpfile.js:

gulp.task('js', function() {
    return gulp.src('./*.js')  //directory of your .js file
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(gulp.dest('./build'));
});

Okay, all we have written all 3 tasks! We're done setting up our tests using gulp! Babel will convert our code to old syntax to work on older browser while gulp-jshint will check for errors in our code.

Step 9: Final Task

Finally, at the bottom of the gulpfile.js, add

gulp.task('default', gulp.series('html', 'css', 'js'));

so that we can run all 3 tests simultaneously.

Your final gulpfile.js should look like:

const gulp = require('gulp');
const htmltidy = require('gulp-htmltidy');
const autoprefixer = require('gulp-autoprefixer');
const csslint = require('gulp-csslint');
const babel = require('gulp-babel');
const jshint = require('gulp-jshint');

gulp.task('html', function() {
    return gulp.src('./*.html') // your html directory
          .pipe(htmltidy())
          .pipe(gulp.dest('build/')); //writes the output, cleanly formatted HTML to the build directory
});

gulp.task('css', function() {
    return gulp.src('./*.css') //your css directory
        .pipe(csslint())
        .pipe(csslint.formatter())
        .pipe(autoprefixer({
            browsers: ['last 5 versions'],  //config to add prefixes to work on older browsers
            cascade: false
        }))
        .pipe(gulp.dest('./build'));
});

gulp.task('js', function() {
    return gulp.src('./*.js')  //directory of your .js file
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(gulp.dest('./build'));
});

gulp.task('default', gulp.series('html', 'css', 'js'));

Your final package.json file should look something like:

{
  "name": "test-project",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "test"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.10.2",
    "@babel/preset-env": "^7.10.2",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^7.0.1",
    "gulp-babel": "^8.0.0",
    "gulp-csslint": "^1.0.1",
    "gulp-htmltidy": "^0.2.4",
    "gulp-jshint": "^2.1.0",
    "jshint": "^2.11.1"
  }
}

Run the tests

Now try to run the command gulp in your project directory to run the automated tests!

You should see something like this:

1.PNG

Looks like I have a lot of errors that are mostly related to using new javascript syntax that will not work on older browsers. If I look into the 'build' folder, I can see my newly formatted html, css and js files that were fixed by running the tests!

Next Steps

Congratulations, you have learned how to set up automated html, css and javascript testing using Node.js, npm and gulp. There is more to testing than just linting and minifying your code so I encourage you to read more on your own. For this particular testing, you can take it further by adding

gulp.task('watch', function(){
  gulp.watch('src/*.html', ['html']);
  gulp.watch('src/*.css', ['css']);
  gulp.watch('src/*.js', ['js']);
});

to your gulpfile.js so that testing will be run whenever you save a file (see documentation for more details).

I hope this has been helpful for you. Do let me know in the comments below if you have any questions regarding this tutorial. Good luck with testing your projects! Cheers!

P.S. : Thank you for all the support on this blog. Some of you have messaged me, wanting to connect through Twitter, so I rebooted my old Twitter account in case any of you would like to follow me on Twitter: twitter.com/lo_victoria2666

No Comments Yet