I’ve been writing a stack of JavaScript test code recently, which often involves writing fixtures that mimic the state of the DOM at any given moment. Writing HTML fixtures in JavaScript is painful though, since JavaScript doesn’t natively support multiline strings, and you don’t really want to have to write all the HTML tags on one line. I decided I had to find a better way of writing fixtures, and had a few conditions to guide my search:

  1. I don’t want to keep my fixtures in a separate file.
  2. I should be able to copy and paste HTML straight from the page’s source. I shouldn’t have to tinker with the HTML to make it parseable.
  3. Something this simple shouldn’t need an extra build step.

I found an open source project by Sindre Sorhus called multiline that allows multiline strings in a JavaScript block comment. It uses some regex magic so I’m hesitant to use this kind of thing in production code, but since I control my own test environment I see no harm in using it there.

Getting this to work is straight forward. Add the multiline module to your codebase:

define(function() {

  var reCommentContents = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//;

  function multiline(fn) {
    if (typeof fn !== 'function') { throw new TypeError('Expected a function'); }
    var match = reCommentContents.exec(fn.toString());
    if (!match) { throw new TypeError('Multiline comment missing.'); }
    return match[1];
  }

  return multiline;
});

…And then import the multiline module into your spec:

var multiline = require('vendor/multiline');

var fixture = multiline(function() {/*
  <form method="post" action="/" class="test-form">
    <p>
      <label for="email">Email</label>
      <input type="text" name="email" id="email">
    </p>
    <p>
      <label for="password">Password</label>
      <input type="password" name="password" id="password">
    </p>
    <input type="submit" value="Sign up">
  </form>
*/});