Skip to content

Comment on Extending JavaScript with inline unit tests

Comments

Here's a simple implementation without sweet.js:

  var inlineTest = function(fn, tests) {
    (tests || []).forEach(function(test){
      if (fn.apply(this, test[0]) !== test[1]) {
        throw new Error('Failed inline unit test with args: ' + test[0]);
      }
    });
    return fn;
  };

  var square = inlineTest(function(n){
    return n * n;
  }, [
    [[2],4], // [[arrayOfArguments], expectedResult]
    [[3],5]  // <-- This test will throw an error
  ]);

EDIT: Change fn.call to fn.apply

Nice. If you wanted to go even more inline:

    Function.prototype.where = function () {
        var fn = this, tests = [].slice.apply(arguments);
        (tests || []).forEach(function(test){
          if (fn.call(this, test[0]) !== test[1]) {
            throw new Error('Failed inline unit test with args: ' + test[0]);
          }
        });
        return fn;
    };
    
      var square = function(n){
        return n * n;
      }.where(
        [[2], 4], // [[arrayOfArguments], expectedResult]
        [[3], 5]  // <-- This test will throw an error
      );

Cool, nice and clean :)

As I mention in the post though, mine is just a very simple macro. But it is enough to show how easy is to modify the language to fit different scenarios, such as testing. The macro could probably be expanded and improved a lot to fit much more complex scenarios like real Contract-based languages have.

you just gave me an idea for a "typechecking" api.thanks.

I wrote something like this once, never did anything with it but you might find it useful: http://jordanwallwork.co.uk/2013/01/faking-typed-function-ov...

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.