Showing posts with label mocha. Show all posts
Showing posts with label mocha. Show all posts

Friday, August 29, 2014

Testing Custom Polymer Elements with Polymer-Test-Tools


I discovered polymer-test-tools last night, but could not quite get them working. While exploring, I began to suspect that they were meant more to support the Polymer project's infrastructure than to help “regular” programmers build elements. Even so, I would like to get them working with my Polymer element, if only to see what polymer-test-tools can teach me about my own testing approach.

I left off last night with a strange SSL / socket.io error. It seemed like an old node.js, but it turns out that I have a relatively recent version of node installed. And, in fact, I no longer see the error tonight. I swear that I have done nothing that could possibly have fixed this, except… it is fixed. Rather than question fortune, I say a prayer of thanks to the gods of the chain and quickly move on before they change their mind.

Not all is well just yet, but I am quite familiar with the next errors thanks to earlier experiments testing Polymer with mocha and chai. First up the before-each failure on start-up:
$ karma start
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
Chrome 37.0.2062 (Linux)  "before each" hook FAILED
        Error: timeout of 2000ms exceeded
Chrome 37.0.2062 (Linux) SLOW 2.003 secs:  "before each" hook
Chrome 37.0.2062 (Linux): Executed 1 of 2 (1 FAILED) ERROR (2.037 secs / 2.003 secs)
I fix this with the same solution from the last time—test setup that relies on Polymer.whenReady() instead of the too-quick polymer-ready event:
// Delay Jasmine specs until Polymer is ready
var POLYMER_READY = false;
beforeEach(function(done) {
  function waitForPolymer() {
    if (Polymer) {
      Polymer.whenReady(done);
      return;
    }
    setTimeout(waitForPolymer, 1000);
  }
  waitForPolymer();

  if (POLYMER_READY) done();
});
I had expected that to be the last of my woes, but I still have another sadly familiar error message to fix:
$ karma start
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket sgWf2bLuHEiLYy7BxgN0 with id 56442994
Chrome 37.0.2062 (Linux)  element content displays click events FAILED
        ReferenceError: expect is not defined
            at Context.<anonymous> (/home/chris/repos/polymer-book/book/code-js/parent_events/test/ClickSinkSpec.js:23:7)
I ran into this same error when I setup mocha on my own, but am surprised to see it with polymer-test-tools. The problem is that the chai framework is not loaded. I am surprised by this because the chai framework is included directly in the polymer-test-tools source. Why include it in the source if it is not going to be enabled by default? I can only guess that the answer has to do with using polymer-test-tools in the Polymer framework code rather than testing custom built Polymer elements.

Whatever the reason, the solution remains the same—I have to alter my karma.conf.js file to include chai in addition to mocha (which polymer-test-tools does include by default):
module.exports = function(config) {
  var common = require('./bower_components/polymer-test-tools/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    frameworks: ['mocha', 'chai'],
    // ...
  }));
};
Only this time, my problem is still not resolved. Since I overrode polymer-test-tools' plugins setting last night, I also have to add karma-chai to it here:
module.exports = function(config) {
  var common = require('./bower_components/polymer-test-tools/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    frameworks: ['mocha', 'chai'],

    plugins: [
      'karma-mocha',
      'karma-chai',
      'karma-chrome-launcher',
      'karma-script-launcher'
    ],
    // ...
  }));
};
After that, all that remains is to change Jasmine's toEqual() and toContain() to chai's to.equal() and to.contain():
  describe('element content', function(){
    beforeEach(function(done){
      document.body.click();
      setTimeout(done, 0); // One event loop for Polymer to process
    });
    it('displays click events', function(){
      expect(el.shadowRoot.textContent).to.contain('Page clicked');
    });
  });
With that, I have all (both) of my tests passing under polymer-test-tools:
$ karma start
...
Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.196 secs / 0.003 secs)
In the end, this really saved me no work. In fact, I had to do a little extra work to disable settings that were not relevant to my on my Linux machine (e.g. IE, Safari testing support). Since I still have to manually install mocha and chai (and setup chai) despite both being included in the polymer-test-tools repository, I save no effort. In other words, this is not a tool for testing custom Polymer elements. Polymer-test-tools is a place for common framework settings to go.

Still, the effort was hardly a complete waste. It is instructive seeing how the Polymer team tests different platforms and browsers (conditionals depending on the operating system). The overall approach seems similar to what I have been using, though I probably ought to investigate a bit more before claiming confirmation of my approach.

Bottom line: I plan to stick with my current approach in Patterns in Polymer.


Day #167

Thursday, August 28, 2014

Getting Started with Polymer-Test-Tools


I can whine for long periods of time about how much better Dart testing is than JavaScript. Loooong periods. But let's face it, that is hardly constructive and, worse, it ignores the hard work of talented folks that are working to make things better.

Last night, I added some simple Dart tests to one of the chapters in Patterns in Polymer. The primary element in that chapter (both the Dart and JavaScript versions of the book) is <click-sink> which, when embedded in another element, will report on events in the containing element. The Dart tests were easy to add, so tonight I do the same in JavaScript.

Until now, my testing solution for JavaScript Polymer has been Karma and Jasmine. It takes a little more work to get these tests working: package.json to install Karma dependencies via NPM, bower.json to install Polymer dependencies via Bower, Jasmine setup for Polymer, etc. In all honesty, it's not that much harder to setup than in Dart.

I would note that the tests just are not as pretty:
  beforeEach(function(done){
    el = document.querySelector('click-sink');
    setTimeout(done, 0); // One event loop for elements to register in Polymer
  });

  describe('element content', function(){
    beforeEach(function(done){
      document.body.click();
      setTimeout(done, 0); // One event loop for Polymer to process
    });
    it('displays click events', function(){
      expect(el.shadowRoot.textContent).toContain('Page clicked');
    });
  });
I really am partial to scheduled_test's schedules:
  test('displays click events', (){
    var el = query('click-sink');
    schedule(()=> document.body.click());
    schedule(() {
      expect(el.shadowRoot.text, contains('Page clicked'));
    });
  });
But I'm not whining!

Instead, I went in search of some other examples of Polymer testing in JavaScript and stumbled across polymer-test-tools, which is a project from the Polymer team itself that has “common tools for testing Polymer elements.” It uses Karma, but instead of Jasmine, it uses Mocha and Chai. I have already investigated both as testing solutions. I remain open to the switch, so let's see if polymer-test-tools can convince me.

It is non-obvious how to use polymer-test-tools, but it has a bower.json, suggesting that I need to add it to my bower.json development dependencies:
$ bower install -D "Polymer/polymer-test-tools"
...
polymer-test-tools#0.4.0 bower_components/polymer-test-tools
Next, I update my karma.conf.js file to pull in the settings from polymer-test-tools:
module.exports = function(config) {
  var common = require('./bower_components/polymer-test-tools/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // Override with my setting here...
  }));
};
I retain some of my own settings—especially the list of the test files—but remove most of what is listed in the common karma configuration. But when I run this, I get warnings about plugins that are not installed:
$ karma start --single-run
WARN [plugin]: Cannot find plugin "karma-mocha".
  Did you forget to install it ?
  npm install karma-mocha --save-dev
WARN [plugin]: Cannot find plugin "karma-browserstack-launcher".
  Did you forget to install it ?
  npm install karma-browserstack-launcher --save-dev
WARN [plugin]: Cannot find plugin "karma-ie-launcher".
  Did you forget to install it ?
  npm install karma-ie-launcher --save-dev
WARN [plugin]: Cannot find plugin "karma-ios-launcher".
  Did you forget to install it ?
  npm install karma-ios-launcher --save-dev
WARN [plugin]: Cannot find plugin "karma-safari-launcher".
  Did you forget to install it ?
  npm install karma-safari-launcher --save-dev
WARN [plugin]: Cannot find plugin "karma-crbot-reporter".
  Did you forget to install it ?
  npm install karma-crbot-reporter --save-dev
I have no desire for most of those, so I override them in my settings:
module.exports = function(config) {
  var common = require('./bower_components/polymer-test-tools/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // ...
    plugins: [
      'karma-mocha',
      'karma-chrome-launcher',
      'karma-script-launcher'
    ]
  }));
};
That still complains about a lack of karma-mocha:
$ karma start --single-run
WARN [plugin]: Cannot find plugin "karma-mocha".
  Did you forget to install it ?
  npm install karma-mocha --save-dev
I had hoped to get this automatically from polymer-test-tools since it includes both mocha and chai:
$ ls bower_components/polymer-test-tools/     
bower.json  chai  htmltest.js  karma-common.conf.js  mocha  mocha-htmltest.js  README.md  tools.html
Alas, this is not the case.

After following the instructions (npm install karma-mocha --save-dev), I run into another problem:
$ karma start
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
ERROR [karma]: [Error: error:24064064:random number generator:SSLEAY_RAND_BYTES:PRNG not seeded]
Error: error:24064064:random number generator:SSLEAY_RAND_BYTES:PRNG not seeded
    at Manager.generateId (/home/chris/repos/polymer-book/book/code-js/parent_events/node_modules/karma/node_modules/socket.io/lib/manager.js:750:12)
    at /home/chris/repos/polymer-book/book/code-js/parent_events/node_modules/karma/node_modules/socket.io/lib/manager.js:805:21
    at Manager.authorize (/home/chris/repos/polymer-book/book/code-js/parent_events/node_modules/karma/node_modules/socket.io/lib/manager.js:931:5)
    at Manager.handleHandshake (/home/chris/repos/polymer-book/book/code-js/parent_events/node_modules/karma/node_modules/socket.io/lib/manager.js:801:8)
    at Manager.handleRequest (/home/chris/repos/polymer-book/book/code-js/parent_events/node_modules/karma/node_modules/socket.io/lib/manager.js:616:12)
    at Server.<anonymous> (/home/chris/repos/polymer-book/book/code-js/parent_events/node_modules/karma/node_modules/socket.io/lib/manager.js:119:10)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2076:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
    at Socket.socket.ondata (http.js:1966:22)
Yikes. Apparently, this is a known issue with Karma. Unfortunately, it looks like I need to install a new node.js. Sigh.

I will call it a night here and maybe pick back up with this tomorrow. While working through this, I am starting to get the feeling that polymer-test-tools is not a general purpose Polymer testing helper. It seems like it helps quite a bit with testing Polymer internals like Shadow DOM, but it may not be appropriate for coders building and maintaining their own Polymer elements. Even so, I may pick back up with this if, for no other reason, than to learn a little from the smart folks behind Polymer.


Day #166

Saturday, August 2, 2014

Switching from Jasmine to Mocha for Testing Polymer Elements


As a Rubyist by trade, I naturally gravitated to the testing syntax boasted by Jasmine. I still rather like it, but maybe it is time for a switch. So let's see how my tests look converted from Jasmine to Mocha

I am using this to test a relatively simple Polymer element, the very excellent <x-pizza>:



There is an SVG version of this element, but I am sticking with this bare-bones JSON version to focus more on testing. I will continue to run the tests with Karma. Also, I am using the Page Objects testing pattern here, so it will be interesting to see how easy it is to migrate my tests (all two of them) from Jasmine to Mocha.

First up, I replace the karma-jasmine dependency in my npm package.json manifest file:
{
  "name": "page_objects",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "karma-mocha": "~0.2.0",
    "karma-chrome-launcher": ">0.0"
  }
}
I try an npm-install, only to be greeted with:
$ npm install 
npm ERR! peerinvalid The package karma does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer karma-mocha@0.1.6 wants karma@>=0.12.8
npm ERR! peerinvalid Peer karma-chrome-launcher@0.1.4 wants karma@>=0.9.3
npm ERR! peerinvalid Peer karma-jasmine@0.2.2 wants karma@>=0.9
...
I agree that Karma, which is currently installed as 0.12.1 does not meet the constraints from karma-mocha:
$ npm ls karma
page_objects@ /home/chris/repos/polymer-book/book/code-js/page_objects
└── karma@0.12.1  peer invalid
But why can't npm figure out that it ought to update Karma? The outdate and update sub-commands have no effect:
$ npm outdated
Package              Current  Wanted  Latest  Location
grunt-contrib-watch    0.5.3   0.6.1   0.6.1  grunt-contrib-watch
grunt                  0.4.2   0.4.5   0.4.5  grunt
$ npm update
...
npm ERR! peerinvalid The package karma does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer karma-chrome-launcher@0.1.4 wants karma@>=0.9.3
npm ERR! peerinvalid Peer karma-jasmine@0.2.2 wants karma@>=0.9
npm ERR! peerinvalid Peer karma-mocha@0.1.6 wants karma@>=0.12.8
I am able to get npm to do the right thing if I completely remove the installed node_modules directory or if I manually install Karma to the latest version:
$ npm install karma
...
karma@0.12.19 node_modules/karma
...
$ npm install
$ npm ls karma karma-mocha karma-chrome-launcher
page_objects@ /home/chris/repos/polymer-book/book/code-js/page_objects
├── karma@0.12.19 
├── karma-chrome-launcher@0.1.4 
└── karma-mocha@0.1.6
I really do not understand that behavior. I doubt I will remember that, so it seems easiest to manually delete node_modules every time that I want to make a significant change to dependencies. Am I missing something?

Anyhow, a npm prune does remove karma-jasmine (as would a rm -rf node_modules), after which Karma will not start:
karma start

/home/chris/repos/polymer-book/book/code-js/page_objects/node_modules/karma/node_modules/di/lib/injector.js:9
      throw error('No provider for "' + name + '"!');
            ^
Error: No provider for "framework:jasmine"! (Resolving: framework:jasmine)
...
That was not unexpected. To resolve, I merely need to change the testing library in my karma.conf.js to use mocha:
module.exports = function(config) {
  config.set({
    // ...
    // frameworks to use
    frameworks: ['mocha'],
    // ...
  });
};
With that, I fire up Karma to find:
$ karma start
INFO [karma]: Karma v0.12.19 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Linux)]: Connected on socket nSCPoCQz6s_jQNBp9kx1 with id 62422835
Chrome 36.0.1985 (Linux)  "before each" hook FAILED
        Error: timeout of 2000ms exceeded
            at /home/chris/repos/polymer-book/book/code-js/page_objects/node_modules/mocha/mocha.js:4288:19
Chrome 36.0.1985 (Linux): Executed 1 of 2 (1 FAILED) ERROR (2.052 secs / 2.001 secs
Ugh.

This is related to my PolymerSetup.js, which I have Karma run before anything else:
// 1. Load Polymer before any code that touches the DOM.
var script = document.createElement("script");
script.src = "/base/bower_components/platform/platform.js";
document.getElementsByTagName("head")[0].appendChild(script);

// 2. Load component(s)
var link = document.createElement("link");
link.rel = "import";
link.href = "/base/elements/x-pizza.html";
document.getElementsByTagName("head")[0].appendChild(link);

// Delay Jasmine specs until polymer-ready
var POLYMER_READY = false;
beforeEach(function(done) {
  window.addEventListener('polymer-ready', function(){
    POLYMER_READY = true;
    done();
  });
  if (POLYMER_READY) done();
});
I dynamically add the script and link tags necessary get the Polymer platform in place as well as the element being defined. That still works fine. Interestingly, both the beforeEach() call and the done() callback in the beforeEach() work the same in Mocha as they had in Jasmine. By virtue of using done as an argument to beforeEach(), the beforeEach() will block all other tests until I call done(). In this case, I will not call done() until I see the usual polymer-ready event.

The problem is not that the polymer-ready event does not fire. Rather it is a question of timing. In Jasmine, the beforeEach() is invoked immediately so that that event listener is in place before the script tags load Polymer. Mocha seems to be waiting for all scripts—even dynamically added one—to load before executing its beforeEach().

There are a couple of ways to work around this, but I opt to use Polymer's whenReady(). First I check for Polymer to be defined. Once it is, I call done() when… Polymer is ready:
var POLYMER_READY = false;
beforeEach(function(done) {
  function waitForPolymer() {
    if (Polymer) {
      Polymer.whenReady(done);
      return;
    }
    setTimeout(waitForPolymer, 1000);
  }
  waitForPolymer();

  if (POLYMER_READY) done();
});
Now that my Polymer test suite is running with Mocha, I can focus on the tests themselves. They still fail with a message about expect not being defined:
ReferenceError: expect is not defined
As an aside, seriously? To run a JavaScript test suites, I need a runner, a testing framework and an assertion library?!

I add karma-chai as another dependency:
{
  "name": "page_objects",
  "devDependencies": {
    "grunt": "*",
    "grunt-contrib-watch": "*",
    "karma-mocha": "*",
    "karma-chai": "*",
    "karma-chrome-launcher": "*"
  }
}
After a rm -rf node_modules; npm install, I update karma.conf.js to include chai as another testing framework (even though it is a assertion library):
module.exports = function(config) {
  config.set({
    // ...
    // frameworks to use
    frameworks: ['mocha', 'chai'],
    // ...
  });
}
And I get a little closer. Now I get an error about undefined not being a function:
        TypeError: undefined is not a function
            at Context. (/home/chris/repos/polymer-book/book/code-js/page_objects/test/XPizzaSpec.js:85:9)
This turns out to be slight syntax mismatch between Jasmine and Mocha Chai. Instead of testing expectations with toEqual, I need to use to.equal():
  describe('adding a whole topping', function(){
    beforeEach(function(done){
      xPizza.addWholeTopping('green peppers', done);
    });

    it('updates the pizza state accordingly', function(){
      var with_toppings = JSON.stringify({
        firstHalfToppings: [],
        secondHalfToppings: [],
        wholeToppings: ['green peppers']
      });

      expect(xPizza.currentPizzaStateDisplay()).
        to.equal(with_toppings);
    });
  });
So, in the end, not much had to change in my actual tests. The page object (the xPizza instance above) is completely unchanged. To switch from Jasmine to Mocha for my Polymer code, I had to change dependencies in npm, change the frameworks listed in the Karma configuration, change the Polymer setup code, and make a minor change to the expectation syntax. I am surprised at how similar everything else is between the two. I am unsure if I will stick with Jasmine or switch to Mocha for the book. Mocha does seem little more active (at least the Karma plugin), but I am not sure that the change would buy readers that much. Something to sleep on, I suppose.


Day #141