Recently I’ve been playing around with NPM. I switched my unit tests from QUnit to Mocha. This was¬†not as straight forward as one would hope. In this blog I’ll show some example code. At the end I’ll link to¬†a side by side comparison of the entire test project. Hopefully it helps you to convert your code. I’ll be using the Chai BDD assertion engine.

QUnit example

Let’s take a look at a QUnit test. It has a module to split your tests up into functional parts. The¬†test method is used to bundle a test. One test can contain one or more¬†asserts to do the actual testing.

Mocha me!

Let’s convert the example into Mocha / Chai. The module can be translated into a describe. The¬†it specifies the test. Note that the execution of the it’s are not synchronous!¬†Each test can be rewritten using¬†expect and¬†to.equal or¬†not.equal.

Fortunately its not that hard to convert QUnit into Mocha if you use the right conversion.

Async – QUnit

What about asynchronous tests? Observe the following test:

Async – Mocha

Now let’s rewrite it. Plugging a¬†function(done) { } into the¬†it method, will cause Mocha to thread the tests as asynchronous. Invoke done¬†when the async test¬†is ready.

Side by side comparison

To make things clearer I’ve put the conversion for the Strongly Typed Events project to a Github Gist comparison:

Side by side comparison QUnit to Mocha on Github Gist

Wrap up

My biggest mistake was using it the wrong way. Just use the following table when converting your tests:

QUnit Example Mocha / Chai Example
module QUnit.module('Events', …¬† describe describe('Events', …
test QUnit.test('Testing something', … it it('Testing something', …
assert equal assert.equal(a, 1, 'A should be 1.') expect /  expect(a, 'A should be 1')
assert not equal assert.notEqual(a, 2, 'A should not be 2.') expect / not.equal  expect(a, 'A should not be 2').not.equal(2)