Testing Express APIs with Tape and Supertest

Our tech world is an ever changing ecosystem where is hard to stay up to date and keep with all the changes. But it’s always nice to add new things to the toolbox, so since the moment I read Eric Elliot‘s post Why I use Tape Instead of Mocha & So Should You back in summer I wanted to try it.

Three weeks ago I got a project to create an Express API with Redis as the database and I felt it was the perfect moment to try the combination of Tape and Supertest. So I did use it and I have to say I’m surprised by the speed and simplicity.

Express API

I’m not going to talk much about setting our API because there are hundreds of good examples on the Internet. But I wan to point out two key points for this testing set-up to work.

The first one is well known. As Supertest expects a function we need to expose our Express app so we can reuse it in our tests.

var express = require('express');
var app = express();
exports = module.exports = app;

But the second one took me a while to figure out and when I saw I’m not the only one having the same issue, I decided to write this blog post.

Tape was running the tests properly but even when I was explicitly finishing all of them with the end() method, the process was hanging indefinitely. This happened because I had two open handles, the http server listening for connections and the connection to the Redis server.

To listen for connections only when our index.js file is called directly by node and not when is required in our tests we need to access the main module.

if (require.main === module) {

And to close the socket connection with the Redis server when no more commands are pending we have the unref() method.

if (process.env.NODE_ENV === 'test') {

With these little tweaks our index.js file should look similar to this one.

 'use strict'; 

// Set default node environment to development 
process.env.NODE_ENV = process.env.NODE_ENV || 'development'; 

var express = require('express'); 
var config = require('./config/environment'); 

// Connect to database 
var redisClient = require('redis').createClient(); 
if (process.env.NODE_ENV === 'test') {   

// Setup server 
var app = express(); 
var server = require('http').createServer(app); 

// Start server 
if (require.main === module) {   
  server.listen(config.port, config.ip, function () {
    console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));

// Expose app 
exports = module.exports = app; 

And now when we run the tape process it will finish outputting the number of running and passing tests.

API testing

Once we have our API ready to work with, setting up the specs is super easy as we just need to require Tape, Supertest and our Express app.

'use strict';

var test = require('tape');
var request = require('supertest');

var app = require('../app/index.js');

For testing a GET request we can call the endpoint and check that what we are actually getting as the response is what we expected to get.

test('GET /things', function (assert) {
    .expect('Content-Type', /json/)
    .end(function (err, res) {
      var expectedThings = [
        { id: 1, name: 'One thing' },
        { id: 2, name: 'Another thing' }
      var actualThings = res.body;

      assert.error(err, 'No error');
      assert.same(actualThings, expectedThings, 'Retrieve list of things');

And for a POST we can create a new object and send it to the API checking again the expected response.

test('POST /things', function (assert) {
  var newThing = { id: 3, name: 'New Thing'};
    .expect('Content-Type', /json/)
    .end(function (err, res) {
      var actualThing = res.body;

      assert.error(err, 'No error');
      assert.same(actualThing, newThing, 'Create a new thing');

These are just really simple examples to showcase the endless possibilities, but Test Driven Development is really possible with this approach avoiding the need of running our API to check every new method.

A newbie in Web Summit Dublin

I spent the first week of November in one massive tech event, the fifth edition of the Web Summit in Dublin with more than 30 000 attendees.

I never really thought about going to Web Summit but on October 14th, shortly after buying tickets for The Next Web Conference next year in Amsterdam, I saw a Facebook Ad offering 100 free tickets to open source contributors. So I logged in with my GitHub account and a week later I got an email announcing that I had won two tickets. I didn’t hesitate much and after contacting my friend Ivan, who works for Google at Dublin, I bought the flight tickets to spend an interesting week in Ireland.


The Web Summit is completely different to any other conference that I’ve ever attended. Talks last 20 or 25 minutes, there is just a single 45 minutes break for lunch and although the content is not that technical, speakers are very big names.

During three days there was 21 focused summits, happening at the same time, in nine different tracks along the two pavilions of the RDS with more than thousand speakers. So even if you try, you can’t be everywhere.

Center stage

The center stage is were all those big names kept rolling by and therefore is where I spent most of the Tuesday listening to people like Stewart Butterfield, the co-founder of the rapidly growing SlackMichael Dell founder of Dell in 1984; Mike Schroepfer the CTO at Facebook; or Mike Krieger, co-founder of Instagram, who closed the Tuesday showing us some old code from the application while explaining how they evolved the “suggested users” algorithm.

To the center stage I also went back on Thursday for the closing remarks of the organizer Paddy Cosgrave and the last talk by the founder of Pixar, Edwin Catmull, twenty years after creating Toy Story.

Sports Summit

As a sports fan I couldn’t miss the chance of seeing some professional sportsmen at the stage, so I spent the other half of the Tuesday and almost the whole Wednesday at the Sports Summit.

I took a a selfie with Chris Froome after his “Marginal gains” talk which I wrote about for a cycling blog in Spanish. And there I also saw a couple of Irish idols like the Olympic boxer Michael Conlan and the golfer Padraig Harrington.

Some sportsmen talked about how they have already moved from the field to the business after retirement. And there was some talks about fantasy sports that is a hot topic not only in the States, but growing in Europe and specially in the UK.

However the highlight for me was “Building for the future: the interactive stadium” with Jed York, CEO of the 49ers, and John Paul, founder of VenueNext, talking about how they built the new Levi’s Stadium thinking already in the future and giving an interactive experience to the spectator through the WiFi and a mobile phone application, that allows them to enter without a paper ticket, order a beer to their seat or immediately watch game’s actions replays.

All these was possible thanks to high tech and infrastructure, with beacons and routers deployed all around the stadium and 40 gigabits per second of bandwidth. In addition they announced that will be bringing the same technology to the New York Yankees and Dallas Cowboys stadiums.

Code Summit

The most awaited day for me as a developer was Thursday because of the Code Summit, so I got there early to be on the first row and take notes.

Surprisingly the best speech had nothing to do with code because Jeff Pulver, pioneer of VoIP, gave us some life lessons in a very emotional talk “Remember to breathe” leaving sentences like “Be who you want to be”, “Live life now”, “Sometimes you are your worst enemy”, “Do something that matters” and “Be good to others”.

Another great talk was that of Bryan Liles who works for Digital Ocean and defined himself as an “Urban American Software Developer”. With “Application ops lader” he told us we should understand the operations of our app based in five points:

  • Continuos integration
  • Continuos deployment
  • Logging
  • Metrics
  • Error handling

And in a really entertaining way gave us some interesting tips like using immutable infrastructure and not touching what is already deployed.

After lunch talks shifted to the security and privacy field where I would like to highlight Mikko Hypponen with “The online arms race”. He started saying that we’ll never produce a piece of code without bugs and every single Fortune 500 company is being hacked. With an example from the Ashley Madison scandal taught us we shouldn’t jump into conclusions and then left the open question “Who do you trust?”. To finish with a goddam IoT kettle that can be used to gain our credentials as a vector to attack our whole network.

Food Summit

I had high expectations for the Food Summit because they said top Irish chefs would be there, so I thought food would be closer to the high cuisine we got at ngEurope in Paris rather than burgers, sandwiches, pizza or fish and chips. Added to the fact that tokens for three lunches cost 50 € and the venue was a 15 minutes walk from the center stage, it was a bit disappointing.

Night Summit

Night Summit is where the real networking happens and I exchanged more business cards in the first night that on any other morning.

Besides the official parties it was really cool of them organizing for the winners of the open source competition a Pub Crawl, that took us to The Bernard Shaw for beers and pizzas and later for some amazing craft beers to the Against the Grain. And what is even better everything was for free, so we felt really pampered and I have to thank Fionnán Alt for organizing the event, giving us the chance to meet other contributors.


Startups are the other big part of the Web Summit aside from the talks, although they get just one of the three days to exhibit. So if you find one interesting, you must talk to them straight away.

As they are sorted by field (Travel, MedTech, Education, Software, Sports & Fitness, Social, eCommerce, etc.) and placed in a one-meter wide boot side by side with the others, sometimes it’s funny to read the descriptions and check that two different teams are doing the very same thing in two distant countries. So I hope after a long day of talking some of them decided to join forces together with a single goal.

In the same sense it’s cool to see some of your past ideas being developed by other people because, as it’s being said many times, an amazing idea without execution is worth nothing. So just walking through the corridors gave me the desire of finally starting to work on one of my ideas.


The Web Summit is an interesting event and if you have an idea I think it’s the right place to try to sell it. And with sell I mean not only to try to get investor’s money but also users or at least put the word out about your idea/app/startup.

Although to get the most of it you should be prepared beforehand and know exactly to who do you want to talk, which speakers do you want to listen and what startups do you wan to visit. Having the time this can be done with the really good mobile application and a bit of research.

The best moment for me was on Wednesday afternoon while queuing for coffee with my friends and wondering what Riverbed was about. As I don’t drink coffee I was the one who went to ask, talked for a while and left my business card for a GoPro HERO4 Silver raffle. Ten minutes later my card was randomly chosen among at least hundred of them and I won the camera, worthy 359€.

And as any other conference it was a great place to meet new people, see old friends and get some refreshing ideas. So thank you again to the Web Summit team for giving us the chance of joining the event at the very last minute!

O’Reilly Open Source Convention in Amsterdam

I have some O’Reilly digital books but I didn’t know they organize conferences too, what I found out just 10 days before the start of OSCON EU in Amsterdam. Luckily at the same time I discovered the GitLab OSCON Challenge 2015 and I decided to spend some hours replicating the design of the speakers page and fill it with my own data, for a chance to win a gold pass.

On Friday, just three days before the start of the conference, I got the happiest Twitter notification ever announcing that I won the gold pass worth 1545 € to access all the sessions, keynotes and tutorials. So once more I have to thank GitLab for giving me the prize and for having such an amazing team (they are hiring), which I got to meet during the event.

Sessions and keynotes (Monday, October 26)

Monday started with the keynotes and some great quotes like “Open source and free software are the same thing. If you want to have an argument about how different they are, you are wrong!” said by Simon Phipps who doesn’t want more open source foundations.

As a JavaScript developer was exciting to see Douglas Crockford on stage; this time presenting The Seif Project which aims to solve the insecurity of the web in five steps:

  • The release of seifnode adding cryptographic services to Node.js.
  • The Seif protocol which is secure JSON over TCP.
  • Resource management to retrieve artifacts by hash.
  • Seif apps built with Node.js and QT.
  • Build a helper app so web browsers can interact with the Seif protocol.

Later in a session he gave a deeper dive into the project and defined what’s wrong with the web ranting against VeriSign and certificate authorities (the only thing they verify is that somebody pay money to somebody else), HTML templating (allows XSS injections), the DOM (worst API ever designed), CSS (Crappy Style Sheets) and the mess of JS (it was written in 10 days and you can make a lot of mistakes in 10 days).

It’s ok to fail could be the summary of Leslie Hawthorn‘s talk where she addressed quite an interesting topic as we are incentivized against failure with shame associated to it. But failure should be a requirement and we should celebrate what we have learned by failing.

Sam Aaron did a great show during the keynote performing music on a Raspberry Pi with Sonic Pi. It was so entertaining that it changed my plans of the morning and I attended his non-scheduled session where I got to know more about the project leaving some great sentences: “We use code for other people to make money. Why don’t we spend more time practicing? Coding is not just for businesses, it’s an amazing tool we have as humans”.

The most inspiring talk of the day was by Mark Bates about how to become a better developer based in five points:

  • practice: always be coding, contribute to other projects, write tests and build your own apps.
  • share: push to open source, fix issues and build your name.
  • write: improve your communication skills writing a blog.
  • perform: give conference talks and learn new topics so you get to ping the world and get free beer.
  • network: leave your laptop at the hotel and get to meet the people and learn something new.

And before the inauguration of the Sponsor Pavilion Job van der Voort explained how GitLab wen from open source to company opening everything, working remotely and therefore communicating asynchronously, being open and respectful, but at the same disagreeing and saying no.

Sessions and keynotes (Tuesday, October 27)

Tuesday started again with more keynotes and Stuart Frisby talking about AB Testing in Booking.com. You should be experimenting; test everything; question what you don’t understand; and prove your boss, the industry and yourself wrong.

It was also fun to see Ninh Bui and Hongli Lai explaining how they bootstrapped a business around open source creating a start-up when your product is available for free and why you shouldn’t be afraid of charging money for it.

However the most impressive keynote for me was David Arnoux explaining Growth Hacking and maybe because it was an unknown topic for me, it even made me thing about changing paths and learn about it.

I attended a couple of database related sessions first with Matthew Revell talking about how to make SQL more JSON friendly, having a look at different technologies (JSONiq, SQL++ and N1QL) and the question of why are we flattening everything. While later it was refreshing to see Curtis Poe faking a database design.

Before lunch Eleanor McHugh and Romek Szczesniak tried to squeeze the one hour talk privacy is always a requirement in just 40 minutes. Technology should protect the awful because everyone gets hacked.

The jaw dropping moment of the conference came after lunch with Scott Jensøn speaking about the future with The Physical Web, where browsers will be able to interact with any device through the use of sensors and beacons to broadcast URLs. This will change the economics of hardware and well, it looks just awesome.

Before the end of the day there was a couple of interesting sessions with Emily Samuels about the insides of the Spotify real-time music recommendation service using Storm and Chris Chabot with some massive facts about China, how Uber changed the restaurant business and democratizing data.

Tutorials (Wednesday, October 28)

Wednesday was tutorial’s day, so I chose to learn a bit of Go Language with John Graham-Cumming although it would have required of a full day training to get something meaningful.

Instead after lunch was stunning to discover Neo4j and graph databases with Michael Hunger and Luke Gannon. We did some really neat stuff with a really expressive syntax and I even got a free book so I can keep exploring it.


This has been one of the most spectacular conferences that I’ve ever attended and not only because of the good topics but the conversations you get to engage with other attendees, sponsors and exhibitors in the corridors. It was great to meet the cool people working at GitLab and GitHub, to discover more about the insides of the engineering teams at Booking.com and PayPal, and to get to know products that before I knew just by name such as Ansible, Couchbase, OpenShift or OpenUI5.

In any case this is a summary about my experience of what I saw at the conference and could be more interesting as a Front-End Engineer; because the conference has four tracks and sometimes even five, so you really need to choose carefully which sessions you want to attend.

Special mention deserves O’Reilly as organizer because everything was smooth including the WiFI for the first time in a conference, so thumbs up as well for the Amsterdam RAI. The badges use RFID technology and once you spend five minutes in a room it gets linked to your profile so you can evaluate later in the mobile application, while exhibitors could scan the badge to get your data which I think is a fine use of the technology.

O’Reilly also had a booth where you can get leaflets and stickers, but what is more interesting they organized book signings with their authors, so I could get JavaScript: The Good Parts signed by Douglas Crockford. Additionally his community manager Josh Simmons is a really nice guy and next year they will be back in Europe with OSCON in London but even better, the Fluent Conference will be held in Amsterdam in November 2016.

The first Polymer Summit in Amsterdam

It’s a long time since I heard about the Polymer project, but I never got the chance to get hands on code, so as soon as I found out about the organization of the first ever Polymer Summit in Amsterdam on September 14-15, I joined without hesitation

Unfortunately, on Monday I couldn’t do much code due to a problem that seems recurrent in every conference I attended and it’s the WiFi not supporting the load and being unstable. It happened during the workshops of ngEurope in Paris and some speakers had problems while showing their examples during the JSConf in Budapest.

So from the fours hours I stayed at the incredible Muziekgebouw aan ‘t IJ venue, more than two were wasted trying to connect to the internet to get something done. Fortunately the code labs will stay online for anybody to try.

Tuesday was a completely different story with a full day of talks and a lot of information to process. From the sixteen talks there were two really powerful: Monica Dinosaurescu almost made me love CSS with Polymer’s Styling System while Laura Palmaro, sharing her story as a visually impaired person, helped to understand better the importance of accessibility with A11y with Polymer.

But the most awesome was to watch on stage two of the greatest web gurus in the world. Addy Osmani showed the Polymer Power Tools with stuff to build, test, lint and serve web components, make them CSP compliant and use a stateless CDN. And Paul Irish performed a live audit of the Google Patents and Polymer Summit website during his Doing a Perf Audit of your Polymer App talk.

To wrap it up the sentence There’s an Element for that by Surma summarizes the exciting future of the web with a great project, that for now still depends of all the major browser vendors copping up with the pace Google is setting with Chrome when implementing web components, so all of us can use them for production changing the way we develop web applications.

Last I have to thank the Polymer Dev Summit team for organizing an amazing event and make it available for free, providing great food, drinks and swag, and giving us the opportunity to meet some fascinating people from all over the world.

Best talks of JSConf Budapest

May 14 saw the birth of a new technical conference in Budapest that I foresee a very good future. For a really affordable price we had two days of great talks in an outstanding venue, with good food and open bar after-parties.

The talks were paired in practical and theoretical with Q&A after each speaker and coffee-breaks in between each pair. So here I would like to highlight those talks that impressed me more or I consider most useful.

For the practical side there are two videos that I would make my team watch as soon as they are up.

On Thursday Sebastiano Armeli of Spotify spoke about Enforcing coding standards in a JS library; and although it might seem simplistic as something we should already know, by experience I know it’s not like that in every team and it’s good to be reminded. The use of editorconfig and code quality tools like JSHint; automate the build process with Gulp or Grunt; unit testing using Karma and Mocha; standards for the commit messages in order to generate the changelog; and Plato, a tool I have to try to check code complexity.

And on Friday it was Sufian Rhazi with Transform your codebase without breaking a sweat who showed us how the front-end infrastructure team of Etsy transformed their large code-base from CSS to SCSS and its moving now the JavaScript to AMD modules. A lot of nice strategies to accomplish it and one important remark for me, which is the importance of hack days so employees can dedicate their time to investigate and try new technologies.

But the most impressive talks were in the creative side as it was astonishing to see what can be done only with JavaScript.

The first one to blow our minds was Martin Kleppe with his Invisible Code talk. I knew about JSFuck before but the things he can write in 140 characters, using 1024 bytes or not using Latin characters at all are extraordinary. You must check the jaw-dropping examples on his website.

Julian Cheal closed the Thursday Dancing with Robots and although half of the widgets didn’t work it was amazing anyway. Like an old magician Julian started to unveil his tricks from controlling the lights of a party to flying (and crashing) a drone with a PlayStation remote. Everything using plain JavaScript and making the audience laugh. It was brilliant.

On Friday Liv Erickson showed us JavaScript for Virtual Reality, mentioned Cardboard (and made me start thinking about buying one) and let us try the Oculus during lunch. While Jaume Sanchez Elias with Getting things done with three.js and WebGL did pretty neat 3D stuff.

These were just some of my favourite talks but all of them were of great quality and there are many more worthy to watch.

Pascal Precht was the representative of the AngularJS community and with Dependency Injection for Future Generations deepened into the new Angular 2.

The announcement of io.js being merged back to node.js came on Thursday so it was interesting to watch Fedor Indutny on Friday answering “political questions” after his Diving into io.js C++ internals talk.

Stephan Bönnemann had a good point about versioning and described it in We fail to follow SemVer – and why it needn’t matter.

And the best possible end for the event was How you can fix your community in one day by Anika Lindtner talking about diversity and inclusion.

Definitely and as I said, a great conference in a beautiful city with a lot of interesting people. Congratulation to the JSConfBP team and see you next year!