Testing a Queue Jobs (kue) in Node JS

We recently started writing a mobile website using Node JS framework. And we use Kue module for creating a queue jobs and processing it in the background. So I’ve decided to share some good techniques of writing a spec tests for Queue Jobs. For these tests we’ll be using the Mocha testing framework along with the Should assertion library.

Mocha is a feature-rich JavaScript test framework running on node.js and the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

As a mocking framework we choose Sinon since it integrates neatly with Mocha and dozens of other test frameworks.

Standalone test spies, stubs and mocks for JavaScript. No dependencies, works with any unit testing framework.

In order to start with writing tests, ensure that Kue, Mocha, Should and Sinon are installed on your system.

Let’s start and create a simple-queue.js script that will be used to enqueue jobs.

As you can see, the method create just creates a queue job with given attributes. And the code .on(`complete/failed`) is an event listener, listening for the events that will be emitted when queue completed or failed.

Now we can get round to actually writing our tests. We’ll create two files, in order to mock the queue jobs and test each queue events from our simple-queue.js script.

Simple Queue Mock:

As you can see, we just created an object KueMock that inherited from EventEmitter. This KueMock object can be used for testing emitters.

Now we can include the KueMock in our specs and test what our simple queue script is emitting internally.

To test that queue job successfully completed, we’ll add event emitter in the beforeEach block and we’ll need to emit `complete` event .

We now have some basic tests that should reasonably cover the simple-queue.js code. If you’d like to have a look at or download and test the full code yourself then it can be found here:

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.