Using CasperJS in automated end-to-end tests for Django applications

2013-03-06 by Senko Rašić

Recently we searched for a good way of writing end-to-end tests covering both the frontend logic (JavaScript) as well as the backend Django system, that could be nicely integrated with the testing framework’s (Django’s & Nose) we already use.

Django has a decent support for automated testing, including end-to-end (or “acceptance”) tests by simulating requests. However, if there’s (significant) logic in the client side JavaScript portion of the web application, Django’s builtin test client will be of limited use. For these cases, Django does have some support for integrating Selenium, but the problem with Selenium is that it’s very hard to reliably run it on a build server, without manual attendance or even a GUI.

Enter PhantomJS, a headless (no UI) webkit-based browser ideal for automating tasks that require a full-blown web browser, such as advanced web scraping or, in our case, testing client-side logic of a web application. For testing purposes, it’s best accompanied by the CasperJS library, which supplies an actual testing framework (whereas PhantomJS is just a browser).

Phantom and Casper make it it easy to test a web service, but they rely on the service being available (running). Since in Django tests we start and stop the server for each test (and setup the fixtures and do any other test setup), we wrote a reusable Django app called Django Casper to glue the two so they work nicely together.

The end result is, we’ve got a single test plan that can run Django and JavaScript unit tests, backend integration tests and full-blown JavaScript enabled acceptance tests and provide an unified result, so we don’t have to maintain (and remember to run, and keep in sync) separate test plans.

We’ve open sourced Django Casper - if you’re testing Django applications and you’re still searching for a good way to integrate JavaScript tests (not neccessarily acceptance tests – we used it to run QUnit tests as well), you should try it out.

Senko Rašić
We’re small, experienced and passionate team of web developers, doing custom app development and web consulting.