Front-end testing with Zombie and Mocha

Testing your code is a good way for you to make sure your application is doing what it’s expected to do. It also provides you more control over what happens when you add new functionalities to your project. If you add a piece of code and your app breaks, tests will help you find exactly where you have to look to fix the issue.

Zombie is a headless browser and Mocha is a testing framework and I chose these tools to test my code. There are a lot of other options to choose from and if your interested, you may find a list of headless browsers here.

So let’s get started. I just mentioned headless browsers, but if you’ve never heard of it before, you’re probably wondering what the heck is that?! A headless browser is a browser without a user interface. So it’s not like Google Chrome where you can interact with it and visualize things on the page, but it does allow other programs to access/interact with the page.

Headless browsers allow us to load up the page and . If there are buttons, we can use Zombie to click on them. This is great for testing because now we can write a program to test the button’s functionality.

To get started we have to

npm install --save-dev zombie 
npm install --save-dev mocha
npm install --save-dev expect

So lets start testing. I have an example that’s testing whether or not when I click on a button called ‘first’, it’ll turn on all the values in a table to ‘undefined’.

So here I’m describing what I’m testing. I’m going to be testing the functionalities of my front end. Then I create an instance of a Zombie browser. The front end has a lot of different steps that can be tested and I’ll do that by using by using it() to test these different cases.

const Browser = require('zombie');
const expect = require('expect');
describe('front end test', () => {
const browser = new Browser();
  it ('press first button makes .variable values undefined', () => {
var counter = 0;
return'#forward', 'click')
.then(() => {
return'#first', 'click');
.then(() => {
const variable = browser.queryAll('.variables');

There’s a lot going on, but don’t fear we’re going to through it step by step!

After we state our test case, we can now use Zombie to start clicking around. I use the .fire method which will make it fire off a click on the button called #forward. Then I tell Zombie to click on the button called #first. Finally I can use Zombie to query for data on the DOM. I’m telling Zombie to get all the DOM elements I’ve named variables.

Then using expect, I can test the data I queried for against what I expected. If the textContent of the variables I queried is ‘undefined’, I’ve passed the tests!

I honestly really enjoy writing tests and it just makes life easier to find where your application is breaking when you have tests!