Integration Tests under Node.js Environment using a mock server

nadavl@wix.com | March 1st 2013 | JavaScript

This week, I was handed a nice task – to integrate with some external service we use, that has no API. All communication with the service was supposed to be mimicking a multiple step scenario of a user integrating with some forms. This means, cookies, sessions, and all the wonders of HTTP protocol..

And, just to add giggles, the whole component is to be written in and act as a part of a NodeJS server.

So, I thought to myself, first thing first; I configured a new NodeJs project with a Jasmine test environment, and started writing my integration tests.

But unfortunately, not only my remote service had no API, there was no way I could create an embedded local service for me to test against!

Popped up Fiddler (or Charles, whatever..) and sniffed the HTTPS traffic as I filled in the forms (Fiddler does it quite elegantly), and created a spec, specifying how should each and every packed look like.

To test it, I created a little HTTP service module, that can store its last request and even stub a response behavior.
It supports HTTP and HTTPS, and made my life easy

Here is some usage examples:

Setting it up:

beforeEach(function(){
	server = new TestableServer(3030);
	server.respondWithStatus(302);
	server.start();
});
afterEach(function(){
	server.stop();
});

And making the actual test:

describe("when executing",function(){
	it("should create the right request to the service",function(){
		cmd.execute( buildTestRequestData(email,session) ,function(){});

		waitsFor(function() {
			  return server.lastRequest != null;
		}, "a request to arrive" , 1000);

		runs(function(){
			expect(server.lastRequest.body["email"]).toBe(email);
			expect(server.lastRequest.headers[SESSION_COOKIE_NAME]).toBe(session);
		});
	});
});

You are more then welcome to grab the source code here:
TestableServer.js


By nadavl@wix.com
Wix

Leave a Reply

We are always looking for excellent people. Browse Jobs Here   

At Wix Engineering we develop some of the most innovative cloud-based web applications that influence our 80+ million users worldwide.

Have any questions? Email academy@wix.com.

Find out what’s coming up at Wix Engineering:

Subscribe to our newsletter for updates, events and more.