Javascript API testing

Testing your javascript library/API

I wrote a small javascript API, HtmlAssert.js, because I needed to be able to test HTML content in javascript for a project I’m working on.

I did it TDD style, with Grunt, Jasmine and PhantomJS.
I used Jasmine to write my unit tests because this API validates HTML content, so I am using the DOM of the HTML document, and in particular, the window.document element to generate an HTML document that I can easily parse in javascript.
Therefore, in order to have the window object, tests need to be executed in a browser (I tried to use jsdom but the c++ compilation part is not straightforward at all, and I don’t have much time to waste).

So with Jasmine, everything was cool, I had my library and my unit tests.

Then came the time to include that API in the project I am working on, and I realized that the best was probably to create a Node.js module.
It is when the chaos started, because my Jasmine unit tests couldn’t be used for a Node.js module with my project stack.

Client-side testing vs Server-side testing.

When you test client-side, you are basically executing your test in a browser and so you have access to the window object.
When you test server-side, you are executing your test in a javascript only stack and you can’t access to the window object.
Jasmine is the testing library that I use to execute my tests.
Grunt is the utility I use to execute my tasks, in particular executing jasmine to run my tests.
When executed from Grunt, grunt-contrib-jasmine is executing tests client-side using PhantomJs as a (headless) browser.
Which means that you don’t have access to Node.JS modules support and the require(“module”); won’t work.
And that is a problem, since you want to use this, in order to test your node module, in the same condition than when you will use your module in a real project.

The other way, running jasmine test server-side is not a good solution either, because you won’t have access to the browser’s window object, so if you are testing browser-related code, it will not work.

Finally I manage to find the solution, using CasperJS, that allows me to run test with node modules and have access to the browser (PhantomJS too) even on the server side.


You can look at my project HtmlAssert.js,
The Gruntfile.js has the definition of the CasperJS task,
inside the /test directory you will see how I wrote my tests using CasperJS’s BDD capabilities.

Please note that I’m a Java developer learning modern javascript, so if you are experienced with javascript, and any part of my explanations seems weird to you, do not hesitate to give your comments!!! Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s