When writing unit tests for our front-end JavaScript code, we often need to specify fixtures: static pieces of data that give the context for the test. A fixture can be a piece of HTML that the JavaScript function under test can operate on. Or a piece of XML that we mock the server to return. Or CSS, etc…

I like to keep my unit tests as self-contained as possible. Navigation is easier when I only have to switch between the code file and the test file and nothing else. So I don’t like to have fixtures in seperate files. The simplest way to keep test fixtures inside the unit test itself, is to use (long) strings, like this:

var context = $('
');

It quickly becomes quite a hassle to edit these long strings, especially when you need to escape quotes or want line breaks. A better way is to put the fixture inside a multiline comment. Using the multiline module from @sindresorhus, it can look like this:

var context = $(multiline(function () {/*
    
*/}));

My jsdevenv-mocha-require demo project on GitHub contains a full working example (using Mocha and RequireJS)

See also my previous blog post CommentReader – Place your test data next to the test code for a similar technique for C#.

Leave a Reply

Your email address will not be published. Required fields are marked *