Showing posts with label testing. Show all posts
Showing posts with label testing. Show all posts

Wednesday, November 25, 2015

Testing Patterns


Tonight, I start testing the code in Design Patterns in Dart. I expect my testing approach will evolve as the book is written. For now, I plan to test code used directly in the book (for obvious reasons) and some of the experimental code that I use to explore patterns before writing.

To start, I will write some tests for the Flyweight pattern coffee shop example with which I have been playing. I start by adding the test packages to the list of development dependencies in my pubspec.yaml:
name: flyweight_code
dependencies:
  reflectable: any
dev_dependencies:
  test: any
transformers:
- reflectable:
    entry_points:
      - bin/coffee_orders.dart
    formatted: true
After a pub get, I start a test/coffee_shop_test.dart file:
library coffee_shop_test;

import 'package:test/test.dart';

import 'package:flyweight_code/coffee_shop.dart';

main(){
  // Tests will go here...
}
With that, I can define some test setUp() to create my flyweight-based coffee shop and place some coffee orders:
  var shop;
  setUp((){
    shop = new CoffeeShop()
      ..order('Cappuccino', 'large', who: 'Fred', fooFoo: 'Extra Shot')
      ..order('Espresso',   'small', who: 'Bob')
      ..order('Cappuccino',     'large', who: 'Alice');
  });
I can test some of the properties of this coffee shop:
  test('it can calculate profit', (){
    expect(shop.profit, 15.2);
  });
  test('it flyweights', (){
    expect(CoffeeFlavor.totalCount, 2);
  });
The profit is based on the cost per ounce of the different coffees. The total count of coffee flavors is determined from the number of flyweight objects in use. Those are both fairly easy tests and do not take much effort to get working. Testing in Dart is still quite pleasant.

I am curious about testing print() statements. I have not had an excuse to do so in any of my Dart code to date, but I happen to use print statements in the serve() method of the coffee shop:
  void serve() {
    _orders.forEach((o) { print("Served ${o.service}.");});
  }
The service property for the orders is something like "Espresso to Bob", so I want to verify that serving drinks prints out the phrase "Served Espresso to Bob". Since there are a number of print() statements throughout the code, I need to verify that all prints contain this phrase. In test parlance, this is expressed as:
  test('prints when serving', (){
    expect(shop.serve, prints(contains('Served Espresso to Bob.')));
  });
So that turns out to be pretty easy! More importantly, the tests all pass:
$ pub run test -r expanded
00:00 +0: test/coffee_shop_test.dart: it can calculate profit
00:00 +1: test/coffee_shop_test.dart: it flyweights
00:00 +2: test/coffee_shop_test.dart: prints when serving
00:00 +3: All tests passed!
So I can test an individual patterns. Now I need to test all of them in the repository. As far as I know, this is the purview of Bash scripts. Fortunately, I have done this before:
#!/bin/bash -e

shopt -s extglob

for X in !(LICENSE|README.md|bin|packages)
do
    # Change the current working directory to pattern directory
    cd $X
    echo "[TEST] $X "

    # Update pub
    echo -n "pub update"
    pub get >/dev/null
    echo " (done)"

    # Run the actual tests
    pub run test
    echo

    # Back to the top-level directory
    cd - >/dev/null
done
This iterates over all files and directories in the repository, except for LICENSE, README.md, bin, and packages. In each code directory, it runs the tests. With that, I have a build script for my book code:
$ ./bin/test.sh
[TEST] flyweight 
pub update (done)
00:00 +3: All tests passed!
I think that I am done now with the Flyweight pattern. I may make a quick check of things tomorrow, but I am likely on to a new pattern.

Day #14


Tuesday, April 7, 2015

Upgrading a Polymer Element to Polymer 0.8


Tonight, I break a rule. Sort of.

Normally in these chains, I think of a question to which I do not know the answer then do my best to answer it. During the course of exploring web-component-tester (WCT) last night, I was quite taken aback at the difficulty involved in upgrading a project from Polymer 0.5 to the new 0.8 (even with the very nice migration guide). I was able to get it working, but without much thought.

So tonight, I revert all of my code changes and start again:
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add/rm ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        modified:   code-js/polymer/elements/hello-you.html
        modified:   code-js/polymer/elements/hello_you.js
        modified:   code-js/polymer/index.html
        deleted:    code-js/polymer/karma.conf.js
        deleted:    code-js/polymer/test/HelloYouSpec.js
        deleted:    code-js/polymer/test/PolymerSetup.js

no changes added to commit (use "git add" and/or "git commit -a")
$ git checkout .
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working directory clean
I can get rid of the Karma tests as I am likely switching to WCT one way or another, but I leave them for now since my CI build expects them.

I will do this work in a new polymerjs-0_8 branch in the Patterns in Polymer book repository. After some thought (and discussion), I think it best for the book to target PolymerJS 0.5 for the time being. Targeting 0.8/0.9/1.0 can wait for the next edition. Still, I need to start playing with it, so let's try to repeat last night's success...

First up, I remove the "polymer": "<0.8" constraint that I added earlier today to my project's bower.json. In this branch, I will again target whatever the latest (semi-)stable version of Polymer is available:
{
  "name": "hello-you",
  // ...
  "dependencies": {
    "polymer": ">0.0"
  }
}
A Bower update and I am ready to roll:
bower update
....
polymer#0.8.0 bower_components/polymer
├── core-component-page#0.5.5
└── webcomponentsjs#0.6.0

webcomponentsjs#0.6.0 bower_components/webcomponentsjs
My tests are failing, but before I even start with that, I update both my sample HTML page and my WCT test page to point to the new webcomponentjs:
    <!-- 1. Load the polymer platform. -->
    <script
       src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
    <!-- 2. Load component(s) -->
    <link rel="import" href="elements/hello-you.html">
My tests are still failing all the same, but this is the most obvious external change required, so it makes sense to start with that.

Next, I start with making sure that my element compiles. I have a sanity test for just this sort of thing. In Polymer 0.5, I would check that my Polymer element had a shadow root element. In 0.8, I need to check for the existence of a "shady" root:
  describe('element content', function(){
    it('has a shady DOM', function(){
      assert.isDefined(el.root);
    });
  });
It does not:
chrome 41                ✖ index.html » <hello-you> » element content » has a shady DOM

  expected undefined to not equal undefined
    <unknown> at   Context.<anonymous> at /polymer/test/index.js:10:0
If I look closer in a persistent WCT browser session, I find:
Uncaught TypeError: undefined is not a function     
desugar                                            polymer.html:37 
window.Polymer                                     polymer.html:21
(anonymous function)                               hello_you.js:2
This is because I can no longer declare my elements in Polymer with the name of the element as the first argument to the Polymer() function:
// 0.5 style:
Polymer('hello-you', {
  // Element definition here...
});
Instead, the element name ("hello-you" in this case) goes in the definition as the is property:
Polymer({
  is: 'hello-you',
  // The rest of the element definition here...
});
With that, I have my sanity test passing:
✓ index.html » <hello-you> » element content » has a shady DOM
One hurdle cleared, but another of my tests is not even registering and the last, which tests clicks, is failing:
✖ index.html » <hello-you> » clicking » randomly changes the title's color

  Cannot read property 'querySelector' of null
    <unknown> at   Context.<anonymous> at /polymer/test/index.js:44:0
I start with the failing test because I can actually see it and, if last night's spike is any guide, the other test will magically reappear after this one is resolved. This is easy enough. I had been looking for child elements in my Polymer element's shadow DOM. There is no shadow DOM anymore (at least not by default), so I can query a little more directly in my tests now:
    it('randomly changes the title\'s color', function(){
      var button = el.querySelector('input[type=submit]');

      var e = document.createEvent('MouseEvent');
      e.initMouseEvent(
        "click", true, true, window,
        0, 0, 0, 80, 20,
        false, false, false, false, 0, null
      );
      button.dispatchEvent(e);

      var h2 = el.querySelector('h2');
      assert.equal(h2.style.color, 'green');
    });
My test still fails, but with a different message:
✖ index.html » <hello-you> » clicking » randomly changes the title's color

  expected '' to equal 'green'
    <unknown> at   Context.<anonymous> at /polymer/test/index.js:56:0
I think I have a legitimate Polymer 0.8 test now, but it does not appear to be interacting with the randomizer button. Checking in the WCT persistent window, I find the following warning:
[input].[click]: event handler [{{feelingLucky}}] is null in scope
It would be nice if warnings like that showed up in the WCT console output because this tells me exactly what the problem is: I can no longer bind methods with the double-curly braces like that. Instead, I have to update my randomizing button to point to the feelingLucky() method with no braces at all:
<polymer-element name="hello-you">
  <template>
    <h2>Hello {{your_name}}</h2>
    <p>
      <input value="{{your_name}}">
      <input type=submit
             value="Fabulousize Me!"
             on-click="feelingLucky">
    </p>
    <p class=help-block>
      <content></content>
    </p>
  </template>
  <script src="hello_you.js"></script>
</polymer-element>
After that my test still fails to pass, but that is a simple code fix—the feelingLucky() method was also pointing to the shadowRoot. After removing that reference, I have two passing tests and... the last test is still missing. I am unsure why that would be, but it seems like a bug in WCT. If I check the console in the WCT persistent browser, I see that I am again using shadowRoot. After removing that from the test, I now get the failure that I desire:
✖ index.html » <hello-you> » typing » says a friendly hello

  expected 'Hello {{your_name}}' to equal 'Hello Bob'
    <unknown> at   Context.<anonymous> at /polymer/test/index.js:33:0
Part of this is easy to solve. Bound variables now have to reside entirely inside of tag. So I update the Polymer template to place {{your_name}} inside a <span>:
  <template>
    <h2>Hello <span>{{your_name}}</span></h2>
    <p>
      <input value="{{your_name}}">
      <input type=submit
             value="Fabulousize Me!"
             on-click="feelingLucky">
    </p>
    <p class=help-block>
      <content></content>
    </p>
  </template>
The other thing that needs to change is the binding of the your_name property inside the <input> element—{{your_name}} by itself will no longer work. In 0.8, I have to append the kind of event that triggers an update to the property. In this case, I want your_name updated when an input event occurs:
  <template>
    <h2>Hello <span>{{your_name}}</span></h2>
    <p>
      <input value="{{your_name::input}}">
      <input type=submit
             value="Fabulousize Me!"
             on-click="feelingLucky">
    </p>
    <p class=help-block>
      <content></content>
    </p>
  </template>
With that, I have all three of my tests for this simple element passing:
✓ index.html » <hello-you> » element content » has a shady DOM
✓ index.html » <hello-you> » typing » says a friendly hello
✓ index.html » <hello-you> » clicking » randomly changes the title's color
And, more importantly, the <hello-you> element again appears to be working:



That was a lot saner than last night. The only thing that I did yesterday, but not today, was converting the <polymer-element> to <dom-element>. I was under the impression that it was required, but it would seem not.


Day #22

Monday, April 6, 2015

Replacing Karma with web-component-tester in Polymer Projects


It looks as though I will be replacing Karma with web-component-tester as the testing framework in Patterns in Polymer. I only really need to do the in the two testing chapters, but I'm in for a penny...

To get started, I will switch testing for the very simple <hello-you> Polymer element from chapter 1 of the book, then upgrade to the latest Polymer to see if anything breaks. That seems like a nice little test of things.

I start by simply replacing the karma dependencies in my chapter's package.json with web-component-tester (WCT):
{
  "name": "hello-you",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-watch": "~0.6.1",
    "grunt-notify": "^0.4.1",
    "web-component-tester": "^2.2.6"
  }
}
I remove the Karma configuration, the test/PolymerSetup.js that was needed in Karma, and the existing node_modules. Then I install the new WCT dependencies:
➜  polymer git:(master) rm -rf karma.conf.js test/PolymerSetup.js node_modules; npm install 
From there, I can convert my tests fairly easily. I had defined the test files in the old karma.conf.js. The web-component-tester expects the test entry point to reside in test/index.html. So I create test/index.html and point it the existing test file:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <link rel="import" href="../elements/hello-you.html">
</head>
<body>
  <hello-you id="fixture"></hello-you>
  <script src="index.js"></script>
</body>
</html>
I also add a fixture in there for easier access to the Polymer element that I want to test.

The tests themselves nearly work without change. I had been using Jasmine for my tests. The BDD interface supported by Chai is very similar to Jasmine—all I need to change is my assert statements:
describe('<hello-you>', function(){
  var el;

  beforeEach(function(){
    el = document.querySelector('#fixture');
  });
  // ...
  describe('typing', function(){
    beforeEach(function(done){
      var input = el.shadowRoot.querySelector('input');
      var e = document.createEvent('TextEvent');
      e.initTextEvent('textInput', true, true, null, 'Bob');
      input.dispatchEvent(e);
      setTimeout(done, 0); // One event loop for Polymer to process
    });

    it('says a friendly hello', function() {
      var h2 = el.shadowRoot.querySelector('h2');
      assert.equal(h2.textContent, 'Hello Bob');
    });
  });
});
Just like that, I have passing tests:
chrome 41                Beginning tests via http://localhost:59285/polymer/test/index.html?cli_browser_id=0
chrome 41                ✓ index.html » <hello-you> » element content » has a shadow DOM
chrome 41                ✓ index.html » <hello-you> » typing » says a friendly hello
chrome 41                Tests passed
Test run ended with great success

chrome 41 (2/0/0)

Done, without errors.
I have another test that relies on Jasmine spies. WCT supports spies, but Sinon stubs instead of Jasmine spies. In this case, I want to stub the return value of Math.random so that the otherwise random color change is deterministic. Sinon (like Jasmine) makes this easy:
  describe('clicking', function(){
    beforeEach(function(){
      // spyOn(Math, "random").and.returnValue(0.99);
      sinon.stub(Math, "random").returns(0.99);
    });

    it('randomly changes the title\'s color', function(){
      var button = el.shadowRoot.querySelector('input[type=submit]');

      var e = document.createEvent('MouseEvent');
      e.initMouseEvent(
        "click", true, true, window,
        0, 0, 0, 80, 20,
        false, false, false, false, 0, null
      );
      button.dispatchEvent(e);

      var h2 = el.shadowRoot.querySelector('h2');
      assert.equal(h2.style.color, 'green');
    });
  });
With that, I again have three passing tests for my simple element:
chrome 41                Beginning tests via http://localhost:37627/polymer/test/index.html?cli_browser_id=0
chrome 41                ✓ index.html »  » element content » has a shadow DOM
chrome 41                ✓ index.html »  » typing » says a friendly hello
chrome 41                ✓ index.html »  » clicking » randomly changes the title's color
chrome 41                Tests passed
Test run ended with great success

chrome 41 (3/0/0)                     

Done, without errors.
My next step is to upgrade the Polymer library to verify that (hopefully) nothing breaks. For the book, I have left Polymer unconstrained in Bower:
{
  "name": "hello-you",
  // ...
  "dependencies": {
    "polymer": ">0.0"
  }
}
So a simple bower update gets me to Polymer 0.8:
$ bower update
...
polymer#0.8.0 bower_components/polymer
├── core-component-page#0.5.5
└── webcomponentsjs#0.6.0

webcomponentsjs#0.6.0 bower_components/webcomponentsjs
With that, I re-run my tests and find… that two tests are now failing:
chrome 41                Beginning tests via http://localhost:42253/polymer/test/index.html?cli_browser_id=0
chrome 41                ✖ index.html » <hello-you> » element content » has a shadow DOM

  expected null to not equal null
    <unknown> at   Context.<anonymous> at /polymer/test/index.js:10:0

chrome 41                ✖ index.html » <hello-you> » clicking » randomly changes the title's color

  Cannot read property 'querySelector' of null
    <unknown> at   Context.<anonymous> at /polymer/test/index.js:44:0

chrome 41                Tests failed: 2 failed tests
Test run ended in failure: 2 failed tests

chrome 41 (0/0/2)                     
2 failed tests
At first, I suspect that there is a newer version of the web-component-tester that I need for Polymer 0.8. Then I take a closer look a the 0.8 Migration Guide and… wow. I am in some serious trouble with 0.8. Not only has the API completely changed, but many of the core concepts that have been baked in to Polymer for nearly two years have changed. Shady DOM? Ouch.

With not _too_ much effort, I am able to get my very simple element migrated to 0.8 and the tests passing again. But I need to give some very serious consideration to how I plan to handle 0.8 in the book. Given that it is only a preview release at this point, I may push to get the latest version of the book done sooner rather than later then deal with the repercussions of 0.8 after the new API stabilizes. Ugh. And I was having such a nice time with web-component-tester.


Day #21

Sunday, April 5, 2015

The Debugger and Breakpoints with web-component-tester


At this point, I am just looking for an excuse not to use web-component-tester. And so far, I have not found one. The web-component-tester (WCT) testing library for Polymer elements seems quite solid. It eliminates a lot of the overhead required for Polymer testing without sacrificing much in the way of configurability or extendability.

But, thanks to a question from Jim Simon in response to last night's post, I might just have the excuse for which I have been looking.

OK, in reality, I am not looking for a reason to dislike WCT. I am simply casting a very critical eye at it before I switch testing solutions in Patterns in Polymer to use it. Until Jim's question, I had yet to find a reasonable objection. Until Jim's question...

So here it is, how do you debug tests in WCT? With Karma, which is the current Patterns in Polymer recommendation for JavaScript, you click the Debug button on the page. Setting breakpoints and using debugger statements work as expected.

I would be satisfied that debugging was solid in WCT if I could simply get a debugger statement to work. So I add one to my Page Objects test from a couple of nights ago:
  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']
      });

      debugger

      assert.equal(
        xPizza.currentPizzaStateDisplay(),
        with_toppings
      );
    });
  });
This seems a useful point to set a debugger statement. The element would have been established by virtue of a fixture and WCT's baked-in wait for Polymer.onReady. In this case, I use the page object's addWholeTopping() method to interact with the element, wait for changes to be done, then wait for the debugger statement to kick-in.

This will not work with my file-watcher setup because debugger statements, like breakpoints, only work if the JavaScript console is open in Chrome. Without that, my tests merrily continue to pass:
Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 52328
Web server running on port 40424 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:40424/js/test/index.html?cli_browser_id=0
chrome 41                ✓ index.html »  » can add toppings to the whole pizza
chrome 41                ✓ index.html »  » defaults » has no toppings anywhere
chrome 41                ✓ index.html »  » adding a whole topping » updates the pizza state accordingly
chrome 41                ✓ simple_tests_01.html »  (1) » starts with no toppings
chrome 41                ✓ simple_tests_02.html »  (2) » starts with no toppings
chrome 41                Tests passed
Test run ended with great success

chrome 41 (5/0/0)                     

Done, without errors.
My first thought at this point is that I need to make use of WCT's persistent option:
$ wct --help

Usage: wct [options]

Options:
   -p, --persistent        Keep browsers active (refresh to rerun tests).
   --root                  The root directory to serve tests from.
   --plugin NAME           Plugins that should be loaded.
   --skip-plugin NAME      Configured plugins that should _not_ be loaded.
   --expanded              Log a status line for each test run
...
I give that a try:
$ wct -p
Starting Selenium server for local browsers
Selenium server running on port 43088
Web server running on port 56994 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:56994/js/test/index.html?cli_browser_id=0
chrome 41                ✓ index.html » <x-pizza> » can add toppings to the whole pizza
chrome 41                ✓ index.html » <x-pizza> » defaults » has no toppings anywhere
chrome 41                ✓ index.html » <x-pizza> » adding a whole topping » updates the pizza state accordingly
chrome 41                ✓ simple_tests_01.html » <x-pizza> (1) » starts with no toppings
chrome 41                ✓ simple_tests_02.html » <x-pizza> (2) » starts with no toppings
...
The tests continue to pass (and not break for debugging). But the test browser remains. I open the JavaScript console:



Then I reload the page, and... the dang page closes the JavaScript console before re-running the tests. My guess is that WCT is doing this because this browser session is still attached to the backend WCT session. When I reload the browser, the WCT session again reports:
...
chrome 41                Beginning tests via http://localhost:56994/js/test/index.html?cli_browser_id=0
chrome 41                ✓ index.html » <x-pizza> » can add toppings to the whole pizza
chrome 41                ✓ index.html » <x-pizza> » defaults » has no toppings anywhere
chrome 41                ✓ index.html » <x-pizza> » adding a whole topping » updates the pizza state accordingly
chrome 41                ✓ simple_tests_01.html » <x-pizza> (1) » starts with no toppings
chrome 41                ✓ simple_tests_02.html » <x-pizza> (2) » starts with no toppings
But what would happen if I start a new window at the same URL, but without that cli_browser_id query string parameter?

There is an easy way to find the answer to that. I open a new Chrome window, open its JavaScript console, and point it to my current WCT server (currently for me at http://localhost:56994/js/test/index.html). With that, I see:



Yay! Debugging.

I can do anything that I normally would in there: look at local variables, check the call stack, step through execution, even interact with objects in the console:



This works just as well with debugger statements in the actual Polymer code and with breakpoints set in the Sources tab. This seems exactly what I need (and hopefully what Jim needs as well).

I think that I will continue to run a file watcher WCT instance during the course of normal development. When things go really wrong, I will stop the WCT instance and bring up a --persistent instance of WCT and a completely separate Chrome window in which I can do the debugging thing. Once I resolve the problem, I can close the persistent WCT session and browser windows, then return to my regularly scheduled file watcher session.

I am rapidly running out of reasons to dislike WCT. But there is always hope for tomorrow.


Day #20

Saturday, April 4, 2015

Better Reporting and Errors in web-component-tester


The sad path with web-component-tester is a little worrisome. So far, web-component-tester (WCT) has handled pretty much everything I had to throw at it with aplomb. It seems every bit a well thought out and implemented test framework for Polymer. But I have mostly worked with successful tests—the happy path. On occasion, something unexpected went wrong and I had trouble figuring out where. That bothered me enough to note, but at the time, I focused on the task at hand.

Now, I look closer at failures—the sad path.

I start by breaking a test intentionally so that I can take a closer look at what WCT reports:
Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 33554
Web server running on port 36678 and serving from /home/chris/repos/polymer-book/play/web-component-tester
firefox 37               Beginning tests via http://localhost:36678/js/test/index.html?cli_browser_id=0
firefox 37               ✖ index.html » <x-pizza> » adding a whole topping » updates the pizza state accordingly

  expected '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["green peppers"]}' to equal '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["red peppers"]}'

firefox 37               Tests failed: 1 failed tests
Test run ended in failure: 1 failed tests

firefox 37 (4/0/1)                    
1 failed tests
I have 5 tests scattered across 4 test files. Which one broke? I know the answer in this case because I intentionally broke it, but had I been merrily coding a separate feature when greeted by this there is no indication of where the failure occurred. My only option would be to hunt for the test description. That would be incredibly tedious if I have multiple tests with the same description (e.g. in different contexts).

I note that using Chrome instead of Firefox will report the bad line number:
chrome 41                ✖ index.html » <x-pizza> » adding a whole topping » updates the pizza state accordingly

  expected '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["green peppers"]}' to equal '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["red peppers"]}'
    <unknown> at   Context.<anonymous> at /js/test/page_objects.js:79:0
That can be easy to miss—especially if I am running more than one browser at a time. So I hope to get richer information from WCT with all browser.

WCT's --verbose option is not the answer. That is a swamp of output that, if anything, makes it harder to find the error. Instead, I try the --expanded option by adding it to my project's wct.cong.js file:
module.exports = {
  expanded: true,
  plugins: {
    local: {
      browsers: ['firefox']
    }
  }
};
Not surprisingly, this results in expanded output:
Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 57440
Web server running on port 53285 and serving from /home/chris/repos/polymer-book/play/web-component-tester
firefox 37               Beginning tests via http://localhost:53285/js/test/index.html?cli_browser_id=0
firefox 37               ✓ index.html » <x-pizza> » can add toppings to the whole pizza
firefox 37               ✓ index.html » <x-pizza> » defaults » has no toppings anywhere
firefox 37               ✖ index.html » <x-pizza> » adding a whole topping » updates the pizza state accordingly

  expected '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["green peppers"]}' to equal '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["blue peppers"]}'

firefox 37               ✓ simple_tests_01.html » <x-pizza> (1) » starts with no toppings
firefox 37               ✓ simple_tests_02.html » <x-pizza> (2) » starts with no toppings
firefox 37               Tests failed: 1 failed tests
Test run ended in failure: 1 failed tests

firefox 37 (4/0/1)                    
1 failed tests
That is of some use, but is not entirely satisfactory. I had not realized earlier that index.html in the output referred to the HTML context of the output. That is the entry point for all of my tests, so I assumed that any failure would be reported from there. In fact, alternate HTML contexts, such as simple_tests_01.html are reported as distinct from the JS tests.

All of my tests are loaded from separate files in index.html:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <link rel="import" href="../elements/x-pizza.html">
</head>
<body>
  <x-pizza id="fixture"></x-pizza>
  <script>
    WCT.loadSuites([
      'simple_tests_01.html',
      'adding_toppings.js',
      'page_objects.js',
      'simple_tests_02.html',
    ]);
  </script>
</body>
</html>
The JS tests are all reported as coming from index.html while the HTML tests are reported as coming from their respective HTML files. With that understanding, I think I can live with this behavior.

Between knowing that I can find the actual line number failure in the output from Chrome and that all browsers will report the correct HTML context, I ought to be fine. For the most part, I imagine that I will just run Chrome tests for development (to keep the runs shorter) and run multiple browsers in continuous integration.

Furthermore, I think it very unlikely that I will ever use multiple JS test suites for a single HTML context like I have done here. I prefer my JS in a separate file, so it is likely that for each simple_tests_01.html and simple_tests_02.html, each will load a corresponding simple_tests_01.js and simple_tests_02.js. So if a test reports failure from a given HTML context, I will know where to start looking. I doubt that I wound ever use two JS contexts as I have done here. As I found last night, doing this makes it easy to confuse your test environment.

So one JS suite for each HTML context will likely resolve my objections. Another potential objection to WCT gone. One way or another, I am definitely sticking with the expanded option. The resulting output may not be as nice as Mocha's spec reporter, but it is close enough for my tastes:
firefox 37               ✓ index.html » <x-pizza> » can add toppings to the whole pizza
firefox 37               ✓ index.html » <x-pizza> » defaults » has no toppings anywhere
firefox 37               ✓ index.html » <x-pizza> » adding a whole topping » updates the pizza state accordingly
firefox 37               ✓ simple_tests_01.html » <x-pizza> (1) » starts with no toppings
firefox 37               ✓ simple_tests_02.html » <x-pizza> (2) » starts with no toppings
firefox 37               Tests passed
Test run ended with great success
It is looking more and more like I need to update a few chapters in Patterns in Polymer.


Day #19

Friday, April 3, 2015

Page Objects and web-component-tester


I am a Page Objects fan. I like page objects for testing web pages, applications, and even Polymer. Tonight, I try to use them with the web-component-tester (WCT).

I typically eschew code reuse in my tests. That is not quite strong enough. More accurately, indirection in tests inspires feelings of anger, bordering on rage. I prefer my test code to be right there in the tests, not scattered around a bunch of files. When something is misbehaving in tests, I loathe searching test code to find the problem.

I make an exception in the case of page objects because they are built primarily around user interactions with applications—code reuse is simply a (tolerable) byproduct. Putting myself in the frame of mind of a human interacting with my applications is where I find value.

I start by adding a new suite to last night's multi-suite WCT for the tasty <x-pizza> Polymer element:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <link rel="import" href="../elements/x-pizza.html">
</head>
<body>
  <x-pizza id="fixture"></x-pizza>
  <script>
    WCT.loadSuites([
      'simple_tests_01.html',
      'adding_toppings.js',
      'page_objects.js',
      'simple_tests_02.html',
    ]);
  </script>
</body>
</html>
I have every reason to expect that page objects will work with WCT. Happily, I am not disappointed. I mostly copy my Karma and Jasmine implementation of Page Objects for this element.

The constructor takes a single element argument:
function XPizzaComponent(el) {
  this.el = el;
}
The methods supported for this element facilitate adding toppings as a human might and reading the results:
XPizzaComponent.prototype = {
  currentPizzaStateDisplay: function() {
    if (this.el.$ === undefined) return '';
    return this.el.$.state.textContent;
  },

  addWholeTopping: function(v, cb) {
    // Select topping from drop-down and click a button here...
    return this.flush(cb);
  },

  flush: function(cb) {
    if (cb === undefined) cb = function(){};
    this.el.async(cb);
  }
};
The most important part of this is the flush() method, which accepts a callback parameter. It invokes Polymer's async() method to ensure that all bound variables are updated and that the UI is updated. Once everything has changed, the supplied callback is invoked. It is useful to invoke flush() directly from tests, but even more useful to invoke it from tests that update the UI—as the addWholeToppings() method does.

This is important for asynchronous testing of Polymer elements. I can supply Mocha's done callback to flush() so that subsequent tests will not run until the element has finished updating itself. So, to test that I can update whole toppings, I call the addWholeTopping() method of the page object and supply the done callback:
  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']
      });

      assert.equal(
        xPizza.currentPizzaStateDisplay(),
        with_toppings
      );
    });
  });
The test itself will not run until the element has completely updated its properties, bound variables, and UI. This is perfect because the test is trying to assert that the element has been updated to include pepperoni.

This works exactly as desired:
Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 58383
Web server running on port 39429 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:39429/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 37               Beginning tests via http://localhost:39429/js/test/index.html?cli_browser_id=1
firefox 37               Tests passed
Test run ended with great success

chrome 41 (5/0/0)                       firefox 37 (5/0/0)                    

Done, without errors.
I am growing fond of WCT. It supports the various kinds of testing that I might want. I still worry that there might be some deficiencies that might give me pause for using it today in Patterns in Polymer, so I will continue to explore tomorrow.


Day #18

Thursday, April 2, 2015

Organizing web-component-tester Test Suites


I like web-component-tester. I just don't know if I like like it.

Actually, I probably do, but I am unsure if I like it enough to go back and rewrite testing chapters in Patterns in Polymer. Certainly I would prefer the option with less work, but not at the expense of an inferior solution. So tonight, I press on in my investigation.

Having gotten my Grunt watcher configuration just right, tonight I experiment a little with the test organization options that are supported by web-component-tester (WCT). I start by simply copying my existing test into separate JS files. The existing test is contained in my project's test/index.html page:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <link rel="import" href="../elements/x-pizza.html">
</head>
<body>
  <x-pizza id="fixture"></x-pizza>
  <script>
    suite('<x-pizza>', function() {
      test('starts with no toppings', function() {
        assert.equal(
          document.getElementById('fixture').pizzaState,
          '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":[]}'
        );
      });
    });
  </script>
</body>
</html>
To load tests, I replace the test suite above with the WCT.loadSuites() method:
<body>
  <x-pizza id="fixture"></x-pizza>
  <script>
    WCT.loadSuites([
      'simple_tests_01.js',
      'simple_tests_02.js',
    ]);
  </script>
</body>
Here, I load two suites which, as the names imply, are very simple. I also retain the <x-pizza> fixture in place in this test/index.html entry point (this may be a mistake, but I leave it for now). The simple tests copy the original test which verifies the initial state of the element:
suite('<x-pizza>', function() {
  test('starts with no toppings', function() {
    assert.equal(
      document.getElementById('fixture').pizzaState,
      '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":[]}'
    );
  });
});
With that, my WCT tests still pass. Thanks to my duplicated test, I now have two passing tests in each of the browsers for which WCT is configured:
Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 48572
Web server running on port 48270 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:48270/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 37               Beginning tests via http://localhost:48270/js/test/index.html?cli_browser_id=1
firefox 37               Tests passed
Test run ended with great success

chrome 41 (2/0/0)                       firefox 37 (2/0/0)                    

Done, without errors.
I am unsure of the best practice for fixture elements. I have the feeling that once a test alters the state, subsequent test suites will see the change instead of the initial, default state. To test that theory, I add a new test that adds a topping to the <x-pizza> element:
<body>
  <x-pizza id="fixture"></x-pizza>
  <script>
    WCT.loadSuites([
      'simple_tests_01.js',
      'adding_toppings.js',
      'simple_tests_02.js',
    ]);
  </script>
</body>
The test itself looks something like:
suite('<x-pizza>', function() {
  var el;

  setup(function(done){
    el = document.getElementById('fixture');
    // Crazy JS to select an item from a drop-down and trigger a
    // change here...

    el.async(done);
  });

  test('can add toppings to the whole pizza', function() {
    assert.equal(
      el.pizzaState,
      '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["pepperoni"]}'
    );
  });
});
The craziness that updates the element is best left for another day. For now, please take it on faith that the elided code makes a change to the <x-pizza> element. And indeed it does since this test passes. Unfortunately, as I feared, it changes the <x-pizza> element for later tests because the last simple test is now failing due to the presence of pepperoni:
...
firefox 37               ✖ index.html » <x-pizza> » starts with no toppings

  expected '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["pepperoni"]}' to equal '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":[]}'

firefox 37               Tests failed: 1 failed tests
Test run ended in failure: 1 failed tests

chrome 41 (2/0/1)                       firefox 37 (2/0/1)      
So, to isolate fixtures, it seems that external test suites need to be HTML suites. I switch simple_test_02.js to simple_test_02.html in the test/index.html entry point:
<body>
  <x-pizza id="fixture"></x-pizza>
  <script>
    WCT.loadSuites([
      'simple_tests_01.js',
      'adding_toppings.js',
      'simple_tests_02.html',
    ]);
  </script>
</body>
And in that HTML suite, I start a completely new WCT test context for my <x-pizza> element. I load WCT, Polymer and import the element itself. Finally I write the test:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <link rel="import" href="../elements/x-pizza.html">
</head>
<body>
<x-pizza id="fixture"></x-pizza>
<script>
suite('<x-pizza>', function() {
  test('starts with no toppings', function() {
    assert.equal(
      document.getElementById('fixture').pizzaState,
      '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":[]}'
    );
  });
});
</script>
</body>
</html>
With that, I have all of my tests passing again:
>> File "test/simple_tests_02.html" changed.
Running "notify_hooks" task

Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 34160
Web server running on port 54777 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:54777/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 37               Beginning tests via http://localhost:54777/js/test/index.html?cli_browser_id=1
firefox 37               Tests passed
Test run ended with great success

chrome 41 (3/0/0)                       firefox 37 (3/0/0)                    

Done, without errors.
It seems safe to say that, if tests rely on fixture data like this, then HTML suites are the way to go. This is perfectly reasonable and not entirely unexpected. Still, it might improve maintainability if WCT can come up with a way to not duplicate the <head> section of each HTML suite. That minor quibble aside, test organization in WCT seems quite easy.


Day #17

Wednesday, April 1, 2015

Headless Polymer Testing with web-component-tester


The browser support in web-component-tester (WCT) is super cool. At first.

But after you run the test suite a few times—or automate it with file watchers—it quickly becomes super annoying. Any browsers that are configured to run tests pop up each time the test suite is run. And if the test suite is scheduled to run each time a change is made to the code, this behavior rapidly grows obnoxious.

So I would like to mitigate or prevent the browsers from popping when the tests are running. I start with mitigation since it is built into WCT via the persistent option. I mark the local WCT task that I am using as persistent in my Gruntfile.js:
module.exports = function(grunt) {
  pkg: grunt.file.readJSON('package.json'),
  grunt.initConfig({
    'wct-test': {
      local: {
        options: {remote: false, persistent: true}
      },
      // ...
    },
    // ...
  });
};
That does not quite work like I hope however. The browsers in which the tests are run are indeed persistent, but they are so persistent that they prevent the WCT task from completing. This leaves me with two windows that have the last state of the element being tested:



And my Grunt watch task is locked after beginning my tests in Chrome and Firefox:
$ grunt watch     
Running "notify_hooks" task

Running "watch" task
Waiting...
Running "notify_hooks" task

Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 47127
Web server running on port 43597 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:43597/js/test/index.html?cli_browser_id=0
firefox 37               Beginning tests via http://localhost:43597/js/test/index.html?cli_browser_id=1
No matter, those persistent WCT grapes were sour anyway.

Instead I am really hoping to get Xvfb working. If I fire up a virtual window system in which the browsers can run the tests, then I never have to see browsers. That should be perfect (and much better than the persistent grapes).

In fact, thank to xvfb-run, this is trivial. All I have to is start my Grunt task with that wrapper script:
$ xvfb-run -a grunt watch
Running "notify_hooks" task

Running "watch" task
Waiting...
Running "notify_hooks" task

Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 42548
Web server running on port 35453 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:35453/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 37               Beginning tests via http://localhost:35453/js/test/index.html?cli_browser_id=1
firefox 37               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 37 (1/0/0)                    

Done, without errors.
Completed in 7.450s at Thu Apr 02 2015 00:36:05 GMT-0400 (EDT) - Waiting..
So I have a passing test and I never have to see a single browser. If I make changes, the test suite is re-run in multiple browsers and I never see a single window.

I very much appreciate xvfb-run's -a option to automatically select a server port. If I have another session running on :99 (the default), xvfb-run will automatically chose an alternate port. Unfortunately, this has the side effect of not working with existing solutions for using Xvfb from within Grunt.

I can probably live with typing xvfb-run -a each time before starting the file-watching WCT test suite. But if I want to keep the command-line to a bare minimum, I can use grunt-shell:
$ npm install grunt-shell --save-dev
Then, in Gruntfile.js, I can load the shell tasks and configure my own:
module.exports = function(grunt) {
  pkg: grunt.file.readJSON('package.json'),
  grunt.initConfig({
    // ...
    shell: {
      test: {
        command: 'xvfb-run -a grunt watch'
      }
    },
    // ...
  });

  grunt.registerTask('default', ['shell:test']);

  grunt.loadNpmTasks('web-component-tester');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-notify');
  grunt.task.run('notify_hooks');
};
If I make the new shell:test the default task (as above), I can start up a file-watching, headless WCT test suite with nothing more than:
$ grunt
Nice! Those are some tasty testing grapes.


Day #16

Tuesday, March 31, 2015

Automated Polymer Testing with Grunt and web-component-tester


Today, I try my hand at combining Grunt and web-component-tester for local Polymer development.

Last night's experiment with Gulp was reasonable successful. Initial setup with Gulp and web-component-tester (WCT) was brilliantly easy. Even the first bits of customization was relatively simple. Quickly, however, I reached a point where I was hip-deep in node.js streams, error handling and the alphabet soup of NPM packages that Gulp uses to make sense of them.

Grunt will certainly require a little more initial effort, but I am all-but-certain that I can get my complete local setup in place. The best laid plans....

What I want is a means to automatically run my tests locally whenever I make a change to code or test files. I also a appreciate a little LiveReload support for my sample pages. I have done both with Grunt before, though not with web-component-tester.

I start by wiping my sample application's package.json file so that I can re-add Grunt, web-component-tester, and a couple of other dependencies that I know that I will want to use:
$ npm install grunt grunt-notify  grunt-contrib-watch web-component-tester --save-dev
This leaves me with a package.json that contains:
{
  "name": "wct_sample",
  "devDependencies": {
    "grunt": "^0.4.5",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-notify": "^0.4.1",
    "web-component-tester": "^2.2.6"
  }
}
I start my Gruntfile.js configuration file with the sample included in the WCT homepage:
module.exports = function(grunt) {
  pkg: grunt.file.readJSON('package.json'),
  grunt.initConfig({
    'wct-test': {
      local: {
        options: {remote: false}
      },
      remote: {
        options: {remote: true}
      },
      chrome: {
        options: {browsers: ['chrome']}
      }
    }
  });

  grunt.loadNpmTasks('web-component-tester');
};
That gives me wct-test:local, wct-test:remote, and wct-test:chrome tasks. The first is the one that will run my test suite (currently just a single test):
$ grunt wct-test:local:chrome
Running "wct-test:local:chrome" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 33822
Web server running on port 35707 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:35707/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 36               Beginning tests via http://localhost:35707/js/test/index.html?cli_browser_id=1
firefox 36               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 36 (1/0/0)                    

Done, without errors.
Nice. That was just as easy to get running as the Gulp version (admittedly there is less configuration with Gulp for the very simple case).

Next, I would like to run my test suite whenever there is a change to any file in the tests or elements directories. This is why I included the grunt-contrib-watch development dependency at the outset. I update Gruntfile.js to include the watch tasks and definitions:
module.exports = function(grunt) {
  pkg: grunt.file.readJSON('package.json'),
  grunt.initConfig({
    'wct-test': {
      local: {
        options: {remote: false}
      },
      // ...
    },
    watch: {
      code: {
        files: ['index.html', 'elements/**'],
        options: {
          livereload: true
        }
      },
      tests: {
        files: ['elements/**', 'test/**'],
        tasks: ['wct-test:local'],
        options: {atBegin: true}
      }
    }
  });

  grunt.loadNpmTasks('web-component-tester');
  grunt.loadNpmTasks('grunt-contrib-watch');
};
The watch:code task will watch the specified files which impact the sample page. On update, they trigger the browser to LiveReload the page (if the extension is being used). The watch:tests task will watch code and test files for changes, running the WCT's wct-test:local task when it sees those changes. For good measure, I specify that the tests should be run at start as well.

And that all works nicely. When I invoke watch, my tests are run right away:
$ grunt watch
Running "watch" task
Waiting...
Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 44706
Web server running on port 37026 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:37026/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 36               Beginning tests via http://localhost:37026/js/test/index.html?cli_browser_id=1
firefox 36               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 36 (1/0/0)                    

Done, without errors.
Completed in 7.828s at Tue Mar 31 2015 23:37:56 GMT-0400 (EDT) - Waiting...
This task does not end, but polls for changes to the specified files. If I make a change to one of them, I find:
>> File "test/index.html" changed.
Running "wct-test:local" (wct-test) task
Starting Selenium server for local browsers
Selenium server running on port 49367
Web server running on port 41348 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:41348/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 36               Beginning tests via http://localhost:41348/js/test/index.html?cli_browser_id=1
firefox 36               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 36 (1/0/0)                    

Done, without errors.
Completed in 7.491s at Tue Mar 31 2015 23:38:18 GMT-0400 (EDT) - Waiting...
To complete my desired setup, I would like to have desktop notifications fire at the end of each test run. This is where the grunt-notify package comes in handy. I want to use "notify hooks” in this case. Whenever a task completes successfully, these hooks will send a desktop notification with the result message.

To use hooks, I have to load the grunt-notify tasks as usual, then run the hooks task:
module.exports = function(grunt) {
  pkg: grunt.file.readJSON('package.json'),
  grunt.initConfig({ /* ... */ });

  grunt.loadNpmTasks('web-component-tester');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-notify');
  grunt.task.run('notify_hooks');
};
That is all that is needed, but I like to specify two configuration options: one to send notifications when the tests succeed (only failure messages are displayed by default) and one to display the message for 8 seconds (instead of the default 3):
module.exports = function(grunt) {
  pkg: grunt.file.readJSON('package.json'),
  grunt.initConfig({
    'wct-test': { /* ... */ },

    watch: { /* ... */ },

    notify_hooks: {
      options: {
        success: true,
        duration: 8
      }
    }
  });

  grunt.loadNpmTasks('web-component-tester');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-notify');
  grunt.task.run('notify_hooks');
};
With that, I see a nice success message when I start Grunt:



And, if I break something, I see:



I might like to see the actual failure message in there, but that is a minor quibble (and a byproduct of WCT since I saw just the one line in Gulp as well). That aside, this is exactly what I want in my test setup and should serve nicely for actual development of Polymer code—something that I will put to the test over the next few days.


Day #15


Monday, March 30, 2015

Gulp and web-component-tester


I hope to build on last night's success with web-component-tester. With relatively little effort or confusion, I was able to write a simple-yet-legitimate test with this newish testing tool for Polymer. Tonight, I would like explore the automated test watching facilities.

First up, I will try Gulp for automated test watchers. I have never used Gulp before, mostly because the "Try Now" button on the homepage takes me to an install page instead of a live demo. I am easily confused by such things, but today I push through and follow the installation instructions so that I can then try.

Global and local install works fine:
$ npm install --global gulp
$ npm install --save-dev gulp
Next, I create a gulpfile.js as recommended on the web-component-tester page:
var gulp = require('gulp');
require('web-component-tester').gulp.init(gulp);
That fails because I do not have web-component-tester installed locally. The wct instructions only mention globally installing it, but it is clearly needed locally for Gulp. So I install it:
$ npm install --save-dev web-component-tester
With that, my package.json now contains:
{
  "name": "wct_sample",
  "devDependencies": {
    "gulp": "^3.8.11",
    "web-component-tester": "^2.2.6"
  }
}
More importantly, my gulplfile.js works and I can run last night's test:
gulp test:local
[23:52:52] Using gulpfile ~/repos/polymer-book/play/web-component-tester/js/gulpfile.js
[23:52:52] Starting 'wct:local'...
Starting Selenium server for local browsers
Selenium server running on port 45226
Web server running on port 33654 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:33654/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 36               Beginning tests via http://localhost:33654/js/test/index.html?cli_browser_id=1
firefox 36               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 36 (1/0/0) 
That is of little use to me, however. The wct command-line from last night does the same exact thing without extra installation and configuration. What I want is a file watcher that will run the test:local task whenever my Polymer code or tests change.

For that, I create a default task in gulpfile.js that establishes a gulp.watch():
var gulp = require('gulp');
require('web-component-tester').gulp.init(gulp);

gulp.task('default', function() {
  gulp.watch(['elements/**', 'test/**'], ['test:local']);
});
Now I can start gulp with no command-line arguments and it will watch for changes:
$ gulp
[00:14:48] Using gulpfile ~/repos/polymer-book/play/web-component-tester/js/gulpfile.js
[00:14:48] Starting 'default'...
[00:14:48] Finished 'default' after 11 ms
...
If I make a change to an of the files being watched, my test runs:
$ gulp
[00:14:48] Using gulpfile ~/repos/polymer-book/play/web-component-tester/js/gulpfile.js
[00:14:48] Starting 'default'...
[00:14:48] Finished 'default' after 11 ms
[00:16:21] Starting 'wct:local'...
Starting Selenium server for local browsers
Selenium server running on port 54671
Web server running on port 42314 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:42314/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 36               Beginning tests via http://localhost:42314/js/test/index.html?cli_browser_id=1
firefox 36               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 36 (1/0/0)                    
[00:16:28] Finished 'wct:local' after 6.29 s
[00:16:28] Starting 'test:local'...
[00:16:28] Finished 'test:local' after 16 μs
I prefer for my test suite to run when I first start a test watched task. To get that to work, I add test:local as a dependency for the default task:
var gulp = require('gulp');
require('web-component-tester').gulp.init(gulp);

gulp.task('default', ['test:local'], function() {
  gulp.watch(['elements/**', 'test/**'], ['test:local']);
});
Now my tests run as soon as I start the default watcher:
$ gulp
[00:24:52] Using gulpfile ~/repos/polymer-book/play/web-component-tester/js/gulpfile.js
[00:24:52] Starting 'wct:local'...
Starting Selenium server for local browsers
Selenium server running on port 47399
Web server running on port 60784 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:60784/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 36               Beginning tests via http://localhost:60784/js/test/index.html?cli_browser_id=1
firefox 36               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 36 (1/0/0)                    
[00:24:58] Finished 'wct:local' after 6.1 s
[00:24:58] Starting 'test:local'...
[00:24:58] Finished 'test:local' after 18 μs
[00:24:58] Starting 'default'...
[00:24:58] Finished 'default' after 13 ms
The only thing left is popup notifications. If there is an easy way to get that working, it escapes me. Upon first pass at Gulp, the streams and events and all are a tad bewildering to me. So in the end, I fall back to manually installing node-notifier:
$ npm install --save-dev node-notifier
From there, I drop the web-component-tester Gulp tasks and directly invoke the testing tasks. If those fail, the I manually send notifications on error:
var gulp = require('gulp');
// require('web-component-tester').gulp.init(gulp);
var wct = require('web-component-tester').test;
var notifier = require('node-notifier');

gulp.task('default', function() {
  gulp.watch('{elements,test}/**', function(done) {
    wct({plugins: {local: {}, sauce: false}}, function(error){
      if (error) {
        notifier.notify({
          'title': 'Build failed',
          'message': '' + error
        });
      }
      else {
        notifier.notify({'title': 'Build passed', 'message': 'Yay!'});
      }
    });
  });
});
That is pretty ugly. It works, but here has to be a simpler way to accomplish. For me, the answer is likely going to be Grunt, which I already use elsewhere in Patterns in Polymer. Unless someone else has an easy way to get this working cleanly in Gulp?


Day #14

Sunday, March 29, 2015

My First web-component-tester Test


Next up in my research-while-awaiting-copy-edits checklist is the web-component-tester. This is probably the most requested topic about which folks have inquired as they read through this blog and the resulting Patterns in Polymer, so this is a great time to investigate.

For better or worse, I use Karma and Jasmine in the book. When I first got started with testing Polymer elements, there were no testing solutions (well Polymer.dart had some, but nothing in JavaScript land). Over time, the solutions that popped up or were suggested did not sit right with me for one one reason or another. Hopefully web-component-tester (wct) will break that trend and, based on the project README, I have every expectation that it will.

I have Java available in my command line $PATH:
$ java -version
java version "1.7.0_75"
OpenJDK Runtime Environment (IcedTea 2.5.4) (7u75-2.5.4-1~trusty1)
OpenJDK 64-Bit Server VM (build 24.75-b04, mixed mode)
So I should be able to install the tool with the usual global node.js NPM install:
npm install -g web-component-tester

> ws@0.5.0 install
...
> sauce-connect-launcher@0.9.3 postinstall
...
> wct-sauce@1.2.0 postinstall
...
> wct-local@1.3.1 postinstall
...
-----
selenium-standalone installation finished
-----
...
/home/chris/local/node-v0.10.20/bin/wct -> /home/chris/local/node-v0.10.20/lib/node_modules/web-component-tester/bin/wct
/home/chris/local/node-v0.10.20/bin/wct-st -> /home/chris/local/node-v0.10.20/lib/node_modules/web-component-tester/bin/wct-st
web-component-tester@2.2.6 /home/chris/local/node-v0.10.20/lib/node_modules/web-component-tester
...
I am using Bower to install Polymer—my bower.json for this sample project is:
{
  "name": "wct_example",
  "dependencies": {
    "polymer": "Polymer/polymer"
  }
}
Since there is no configuration (e.g. via .bowerrc), Polymer and the associated webcomponentjs package gets installed in the bower_components directory. I am testing a favorite from Patterns in Polymer, <x-pizza>, whose definition resides in the elements subdirectory. I adapt the setup in the sample wct page accordingly:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <!-- <script src="../../webcomponentsjs/webcomponents.min.js"></script> -->
  <script src="../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <link rel="import" href="../elements/x-pizza.html">
</head>
<body>
  <x-pizza id="fixture"></x-pizza>
  <script>
    // Tests will go here...
  </script>
</body>
</html>
I am unsure why the sample given on the project page uses the "../../webcomponentsjs/webcomponents.min.js" location for the webcomponents library. In my sample, that resides outside of the project directory entirely. Regardless, if this file is stored in test/index.html, then the "../bower_components/webcomponentsjs/webcomponents.min.js" location works for me. Additionally, I <link> import the <x-pizza> element definition and establish it as a fixture for my tests.

Next up, I write a simple test of <x-pizza>. To start, I would simply like to assert that it starts with no toppings:
    suite('<x-pizza>', function() {
      test('starts with no toppings', function() {
        assert.equal(
          document.getElementById('fixture').pizzaState,
          '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":[]}'
        );
      });
    });
Amazingly, that works:
$ wct test/index.html
Starting Selenium server for local browsers
Selenium server running on port 35270
Web server running on port 33741 and serving from /home/chris/repos/polymer-book/play/web-component-tester
chrome 41                Beginning tests via http://localhost:33741/js/test/index.html?cli_browser_id=0
chrome 41                Tests passed
firefox 36               Beginning tests via http://localhost:33741/js/test/index.html?cli_browser_id=1
firefox 36               Tests passed
Test run ended with great success

chrome 41 (1/0/0)                       firefox 36 (1/0/0) 
I realize that was a very simple test, but I am extremely happy with how easy it was to get wct setup and to run my first test. I do not have a strong opinion on Jasmine vs. Mocha/Chai—they are fairly interchangeable in my mind. So all in all, this seems a nice win for testing—especially since wct hides any Polymer/ready waiting. The proof will come with more complicated tests, on which I start tomorrow.


Day #13

Saturday, March 21, 2015

Scheduled Polymer and Angular (Dart) Tests


I continue to evaluate Patterns in Polymer against the latest pre-release version of Polymer.dart (0.16). Last night I verified that Angular.dart solution from the book still works. Previously, I verified that simple testing still works. Tonight, I hope to verify that testing with Angular.dart works—thus verifying that more complex testing is still working with Polymer.dart 0.16.

I'm fond of scheduled_test for testing asynchronous Dart code. It sits right on top of the standard unittest, so most of the usual methods and matchers work. What it adds to unittest is nicer support for scheduling otherwise asynchronous actions in order, making tests for this type of code deterministic.

The scheduled_test version of the simple, Polymer 0.16 test from the other day is:
library angular_test;

import 'package:scheduled_test/scheduled_test.dart';
import 'package:unittest/html_config.dart';
import 'package:polymer/polymer.dart';

main() {
  useHtmlConfiguration();
  initPolymer();

  var _el;
  group("<x-pizza>", (){
    setUp((){
      schedule(()=> Polymer.onReady);

      schedule((){
        _el = createElement('<x-pizza></x-pizza>');
        document.body.append(_el);
      });

      currentSchedule.onComplete.schedule(() => _el.remove());
    });

    test('has a shadow root', (){
      schedule(() =>
        expect(query('x-pizza').shadowRoot, isNotNull)
      );
    });
  });
}
I import the testing, test output formatter, and Polymer packages. In the main() entry point, I use the test formatter and initialize Polymer, then I start my test. In setUp(), I have two schedules. The first returns the Polymer.onReady future. The scheduled_test library will wait until this future completes before running any other schedules. So, in setUp(), the custom <x-pizza> Polymer element will not be added to the test page until Polymer is ready to process it—perfect! The last bit of code in setUp() is the scheduled_test version of a tear-down block—it removes the custom element after the test is executed.

As for the test itself, it schedules the expectation that the shadow DOM of the custom element is present—a very basic sanity check that Polymer is working. It is important that this test wrap a schedule. Without it, this test will run before the setUp() schedules, which are placed into a queue. In other words, omitting the test schedule would evaluate expectation before Polymer was ready and before the element had been added to the page.

That test passed, but what about a Polymer test on an Angular page? The Angular.dart package contains a lot of testing infrastructure, but I find it hard to use for application testing. It seems of more benefit for testing Angular itself, which is its purpose after all.

So I create an entire application in my test:
    group("angular", (){
      XPizzaComponent xPizza;

      setUp((){
        schedule((){
          var app = new PizzaStoreApp()
            ..bind(NodeBindDirective)
            ..bind(RouteInitializerFn, toValue: storeRouteInitializer);

          applicationFactory()
            .addModule(app)
            .rootContextType(Pizza)
            .run();
        });
        // More schedules here...
      });
      // Tests here...
    });
The PizzaStoreApp() and router are dumbed-down versions of the ones used in the actual application. It is probably a mistake on my part, but my router actually points to a separate page in my test directory:
void storeRouteInitializer(Router router, RouteViewFactory views) {
  views.configure({
    'custom-pizza': ngRoute(
        defaultRoute: true,
        view: 'custom.html'
      )
  });
}
I am purposely trying to test that my Polymer element works when used in an Angular route, so I need something like this, but I am unsure if this is the best way to go about doing so. If nothing else, this requires me to wait for the custom.html partial to be loaded and inserted into the view. And I have no idea how to do this in Angular.dart, so I cheat:
    group("angular", (){
      setUp((){
        schedule((){ /* Schedule Angular app setup */ });o
        schedule((){
          var _completer = new Completer();
          new Timer(new Duration(milliseconds: 50), ()=> _completer.complete());
          return _completer.future;
        });
        // ...
      });
    });
If this were AngularJS, I could wait for a $viewContentLoaded event before completing this schedule. Unfortunately, there is no Anguar.dart equivalent for this event. So I am forced to wait some arbitrary amount of time. Ew.

Ugliness aside, my tests still work. I can verify that an Angular value bound to my Polymer element is updated in response to a change in the Polymer element:
      test('can double-bind to Polymer properties', (){
        schedule(()=> xPizza.addWholeTopping('green peppers'));
        schedule((){
          var angular_el = document.query('pre');
          expect(
            angular_el.text,
            contains('"whole":["green peppers"]')
          );
        });
      });
The xPizza object is a Page Object that makes testing interaction a little clearer in my tests. In the end, these (and other) tests pass with the latest Polymer.dart:
PASS
1       PASS
Expectation: <x-pizza> has a shadow root .

2       PASS
Expectation: <x-pizza> defaults to a blank pizza .

3       PASS
Expectation: <x-pizza> adding toppings updates the pizza state with new toppings .

4       PASS
Expectation: <x-pizza> angular can double-bind to Polymer properties .

All 4 tests passed
I really ought to get a better handle on testing Angular applications, but the hack that I have been using all along in Patterns in Polymer continues to work.



Day #5

Thursday, March 19, 2015

Simple Solutions to Asynchronous Polymer.dart Testing


In the development release of Dart and Polymer.dart, the simplest that I can write is still complex:
  group("<hello-you>", (){
    setUp((){ /* Add element here... */ });

    test("has a shadowRoot", (){
      Polymer.onReady.then(expectAsync((_) {
        expect(
          query('hello-you').shadowRoot,
          isNotNull
        );
      }));
    });
  });
I add my custom element to the page and expect that, by virtue of Polymer goodness, it has a Shadow DOM. This is not a completely useless test—verifying that Polymer is decorating an otherwise unknown HTML element tells me a lot. Still, it would be nice if there was not so much… asynchronous goop obfuscating an otherwise simple expectation.

At its heart, this test is just:
        expect(
          query('hello-you').shadowRoot,
          isNotNull
        );
But it is hard to see with everything else that needs to take place to ensure that the test runs and that it runs in content_shell, the dirt-simple headless testing solution for Dart.

My last thought yesterday remains my first thought tonight. Why not simplify this with a Polymer-specific test matcher? This turns out to be the wrong idea, but bear with me...

I start with a function that tries to wrap the expected asynchronous call like so:
polymerExpect(actual, matcher) {
  Polymer.onReady.then(expectAsync((_) {
    expect(actual, matcher);
  }));
}
The main reason that this is wrong is that the actual value would have already been determined before this helper method is invoked. That is, if I try to rewrite my test with this helper, it would look like:
    test("has a shadowRoot", (){
      polymerExpect(
        query('hello-you').shadowRoot,
        isNotNull
      );
    });
Since there is no wait-for-Polymer or any other delay in here, this code is evaluated immediately. I query for the <hello-you> element in the test page and send its shadowRoot into polymerExpect() without waiting for Polymer to be ready. In other words, I send null as the "actual" value—not what I want.

While contemplating how to rewrite this so that evaluation of the shadowRoot can be deferred, I finally realize how I should have done this from the start—and it does not even require using the scheduled_test asynchronous wrapper around unittest.

If the setup() block in unittest returns a Future, the test runner will block until that Future completes. So all I have to do is return Polymer.onReady from setup():
  group("<hello-you>", (){
    setUp((){
      // Add the element here...
      return Polymer.onReady;
    });

    test("has a shadowRoot", (){
      expect(
        query('hello-you').shadowRoot,
        isNotNull
      );
    });
  });
With that, my test is as simple (and readable) as possible and it runs in Dartium and content_shell alike.

I feel pretty dumb for not recognizing that before. As penance for my stupidity, I write two new tests for this element. It is from an example very early in Patterns in Polymer, so it does not have ID attributes to make it easier to find elements within the shadow DOM. That aside, the tests are fairly straight forward:
    test("name updates the template", (){
      _el.your_name = "Bob";
      _el.async(expectAsync((_){
        var h2 = _el.shadowRoot.querySelector('h2');
        expect(h2.text, 'Hello Bob');
      }));
    });

    test("color changes", (){
      var h2 = _el.shadowRoot.querySelector('h2');
      expect(h2.style.cssText, '');

      _el.shadowRoot.querySelector('input[type=submit]').click();
      _el.async(expectAsync((_){
        expect(h2.style.cssText, startsWith('color'));
      }));
    });
The <hello-you> element has the your_name property bound to the <h2> of its template. The first test verifies that the <h2> contains “Bob” if the your_name property is set to "Bob". The second verifies that the <h2> starts life without a color style, but is randomly assigned a color when the button in <hello-you> is clicked.

Both tests rely on my old friend async(), which mostly ensures that the Polymer UI and computed properties have been updated. With those tests added, I have three tests passing:
PASS
1       PASS
Expectation: <hello-you> has a shadowRoot .

2       PASS
Expectation: <hello-you> name updates the template .

3       PASS
Expectation: <hello-you> color changes .

All 3 tests passed
The added tests are nice (and verify that multiple tests work), but the real win is removing the unnecessary asynchronous code from my tests. Many Polymer tests involve some form of asynchronous code. Best not to start with things cluttered.


Day #3