Mocha string diffs

Mocha 0.14.0 adds a single feature - string diffs! This is a small but very handy feature for some. When the strings are small, Mocha will use a character diff, when consisting of several lines a line-numbered “gutter” is added and a word diff is used as shown in the following image:

mocha string diff example

This is very useful when authoring things like template engines, transpilers, and other string-based libraries. For example the Stylus test suite is comprised of nothing but acceptance tests, the input file is compiled, and the resulting CSS is checked using actual.trim().should.equal(css);. In combination with Mocha’s BDD interface I can now simply iterate through the files and define test-cases as shown here:

  var stylus = require('../')
    , fs = require('fs');

  // test cases

  var cases = fs.readdirSync('test/cases').filter(function(file){
    return ~file.indexOf('.styl');
  }).map(function(file){
    return file.replace('.styl', '');
  });

  describe('integration', function(){
    cases.forEach(function(test){
      var name = test.replace(/[-.]/g, ' ');
      it(name, function(){
        var path = 'test/cases/' + test + '.styl';
        var styl = fs.readFileSync(path, 'utf8');
        var css = fs.readFileSync('test/cases/' + test + '.css', 'utf8');

        var style = stylus(styl)
          .set('filename', path)
          .include(__dirname + '/images')
          .include(__dirname + '/cases/import.basic')
          .define('url', stylus.url());

        if (~test.indexOf('compress')) style.set('compress', true);

        style.render(function(err, actual){
          if (err) throw err;
          actual.trim().should.equal(css);
        });
      })
    });
  })

Now if something were go to wrong, you get a nice diff!

stylus diff example

Assertion library authors

To support this feature all you have to do is populate err.expected and err.actual with their respective values, Mocha will take care of the presentation.

NOTE: I just toggled the colors, green is now the expected color

Notes

  1. kazupon reblogged this from tjholowaychuk
  2. tjholowaychuk posted this