Skip to content

A basic example to set-up automated testing with Gulp and Mocha

Notifications You must be signed in to change notification settings

Ariflo/GulpMochaAutomatedTesting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 

Repository files navigation

calm

Automated Testing with Gulp-Mocha

Never fear, automated Test Driven Development (TDD) is here!

This repository will outline the steps necessary to set-up an automated Gulp-Mocha testing suite for your SEAN (PostgreSQL, Express, Angular, Node) web app.

###File Structure This demo assumes your SEAN app follows the standard MVC file structure:

$tree
├── bin
├── db
├── node_modules
├── models
├── public
│   ├── css
│   ├── partials
│   ├── templates
│   └── js
│       └── main.js
│       └── services.js
│       └── directives.js
│       └── controllers.js
│       └── filters.js
├── routes (controller)
│   └── index.js
└── views
│	 ├── error.ejs
│	 └── index.ejs
├── app.js
├── gulpfile.js
├── knexfile.js
├── package.json

If not, feel free to type yo galvanize-fullstack into your terminal's command line to get a basic SEAN app skeleton. See the npm details here

##Step 1: Install the Gulp Test Suite

You will first need to enter the following into your terminal command line

$ npm i  gulp mocha chai gulp-mocha gulp-util supertest supertest-session -g
$ npm i  gulp mocha chai gulp-mocha gulp-util supertest supertest-session --save

For the inquisitive among us:

  • Gulp is a build system that will assist in running the test code. I like to think of it as a task manager that can watch for file changes and trigger tests automatically.

  • Mochais a test framework that will provide the instruments needed to run the actual test. A popular alternative to Mocha is Jasmine. You can learn more about the diffrence between the two here.

  • Chai is a BDD / TDD assertion library for node and the browser that, as noted on the site, can be delightfully paired with any javascript testing framework. Not sure how something can be 'delightfully paired' but it certainly helps to have chai around when building your actual tests.

  • Supertest is a module that can provide a high-level of abstraction for testing HTTP (ie.routes), while still allowing you to drop down to the lower-level API provided by super-agent. In layman terms, no crossing ports! You can test your express app's routes and not have to worry about whether the app is running or not. It truly is super!

##Step 2: Create and Build your gulpfile.js

You'll want to create a gulpfile.js if you don't have it already

$ touch gulpfile.js

Now, you'll need to make sure to require the gulp build system you installed earlier at the top of the gulpfile:

var gulp = require('gulp');
var mocha = require('gulp-mocha');
var util = require('gulp-util');

Its tasking time!

Like I mentioned before gulp is essentially a task runner that wants to excute a list of commands you've provided for it to do.

With this in mind, lets add a couple of tasks to our gulpfile:

/**
 * Gulp Tasks
 */
 
gulp.task('test', function () {
    return gulp.src(['test/**/*.js'], { read: false })
        .pipe(mocha({ reporter: 'spec' }))
        .on('error', util.log);
});
 
gulp.task('watch-test', function () {
    gulp.watch(['views/**', 'public/**', 'app.js', 'routes/**', 'test/**'], ['test']);
});

// *** default task *** //
gulp.task('default', ['test', 'watch-test'], function(){});

Great! Now when you run $ gulp, it will excecute the ‘default’ tasks provided, which in this case is to simultaneously run our two other tasks test and watch-test.

  • 'test' has the duty of actually running our mocha tests. Using 'gulp.src' it will search through our test folder and run any files inside. It'll run them under the standard 'spec' hierarchical view and log any errors.

  • 'watch-test' has the duty of checking for changes to any of the specifed folders or files in the app. As soon as 'gulp.watch' sees a change to any of the files it will automatically run the 'test' task and report the results in the terminal.

Check out the gulp-mocha npm page to learn more about the cool stuff you can do.

##Step 3: Create a Test Folder and and Build your Test File

Alright, now that you've got the tasker ready to run tasks you'll need to set-up tasks for it to run (trying saying THAT 3x fast!)

Lets create our test folder where we'll keep all of our test.js files

$ mkdir test
$ cd test 

While inside the test folder in your terminal create a test file: $ touch firstTest.js

At the very top of your test file you should establish the port and enviorment

process.env.PORT = 5000;
process.env.NODE_ENV = 'staging';

In order to gurantee the development and testing enviorments won't compete for ports, make sure to set the port to something other than what's been set for development in your app.js (server) file.

I cannot re-emphasize this enough:

Make sure to set the port to something other than what's been set up for development!!!

You will also need to make sure you have a 'staging' enviorment set-up in your database file (ie. knexfile.js)

Next, you will need to bring in a few more requirements:

var request = require('supertest')
	, app = require('../app')
	, expect = require('chai').expect
	, session = require('supertest-session');

As I mentioned before, supertest is our main testing framework. In order to properly send routes to your sever you will need to also require the server in the test file (in this case app.js).Chaigives us the ability to use 'expect' (see my sample code below) and finally Supertest provides a handy cookie-based session persistence tool called supertest-session to envolpe our app (ie. server).

It isn't particularly mandatory, but when starting out I would set-up a beforeEach where you assign a variable to the session. It cleans up the code a little and makes it easier to understand what your test is doing.

beforeEach(function () {
  testSession = session(app);
})

Congrats! You are offcially ready to build your tests!

In the sample that I've attached to this repository I test to see that my app is able to load the dashboard (homepage) successfully:

describe('this test', function(){

	it("should load the dashboard", function(done){
		testSession.get('/')
		.expect(200)
		.end(function(err, res){
			if(err){
				return done(err);
			}
			expect(res.text).to.contain('Galvanize');
			done();
		})

	})

})

##Welcome to the Wonderful World of Test Driven Development

Now that everything is in place, feel free to run your development enivorment sever using nodemon in one terminal window. While on another window simply type gulp into your command line and hit enter.

You should now feel the weight of the world lift off of your shoulders.

over

When you return to your code, you can make any and all necessary changes, save your code, and simply look at your terminal window and hope to see those magnificant beautiful green checkmarks assuring you that it's ok to walk away from the laptop. You're free!

More on writing tests in mocha
More on writing tests in jasmine

About

A basic example to set-up automated testing with Gulp and Mocha

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages