Lexing JavaScript with assert_js

To test JavaScript without writing an entire web browser in Ruby, install Ruby's venerated ancestor Perl, and then install this package:

http://corion.net/perl-dev/Javascript-PurePerl-0.08.tar.gz

It contains a lexer that converts JavaScript into XML describing each lexeme. Write this little snip of Perl into a file called jsToXml.pl:

  use strict;
  use Javascript::PurePerl;

  open(JS, 'tmp/sample.js');
  read(JS, my $source, -s JS);
  close(JS);
  my $tree = Javascript::PurePerl->new()->parse( code => $source );

  print $tree->toString,"\n";

It reads a temporary file called sample.js, converts its contents to XML, and emits that to its stdout. We can wrap that Perl up in this Ruby assertion:

  def assert_js(source)
    File.open('tmp/sample.js', 'w'){|f|  f.write(source)  }
    assert_xml `perl jsToXml.pl`

    assert_xpath '/AST/Program/SourceElements' do |node|
      yield(node) if block_given?
    end
  end

The program jsToXml.pl returns a big XML tree, packed with every obscene detail of your JavaScript. Where your JavaScript had a simple term like "Ajax.Updater", Javascript::PurePerl explains it all, like this:

  <MemberMemberExpression name='ClassExpression'>
    <Identifier name='lhs'>Ajax</Identifier>
    <Identifier name='member'>Updater</Identifier>
  </MemberMemberExpression>

Nobody should write assertions for all of that! We only need to query into that huge database, and fetch out a few specific details. And that's where assert_xpath shines:

 def test_assert_js yaml_to_xhtml(get_omap) hammy_id ...

Get Test Driven Ajax (on Rails) now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.