Showing posts with label page objects. Show all posts
Showing posts with label page objects. Show all posts

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

Friday, December 19, 2014

On Polymer, Protractor, and Page Objects


Tonight, I continue to abuse Protractor, forcing it to perform end-to-end (e2e) tests against Polymer instead of its preferred AngularJS. Protractor provides some facilities for testing non-Angular applications, but is hampered in testing Polymer elements since the underlying WebDriver does not support the Shadow DOM on which Polymer relies heavily. Even so, it has already provided useful insights into my Polymer element—and made for some pretty tests.

The Polymer element that is being tested remains an early version of the <x-pizza> pizza builder used extensively in Patterns in Polymer:



Last night's test veered a bit away from pretty tests, mostly thanks to a call to Protractor's browser.executeScript(), which I use to workaround WebDriver's lack of shadow DOM support. Said script comes in the form of a brutal string:
describe('<x-pizza>', function(){
  beforeEach(function(){
    browser.get('http://localhost:8000');
    expect($('[unresolved]').waitAbsent()).toBeTruthy();
  });
  it('updates value when internal state changes', function() {
    var selector = 'x-pizza';
    browser.executeScript(
      'var el = document.querySelector("' + selector + '"); ' +
      'var options = el.shadowRoot.querySelectorAll("#firstHalf option"); ' +
      'options[1].selected = true; ' +
      '' +
      'var e = document.createEvent("Event"); ' +
      'e.initEvent("change", true, true); ' +
      'options[1].dispatchEvent(e); ' +
      '' +
      'button = el.shadowRoot.querySelector("#firstHalf button"); ' +
      'button.click(); '
    );
    expect($(selector).getAttribute('value')).
      toMatch('pepperoni');
  });
  // ...
});
The code in there is ugly enough to begin with, but why-oh-why does Protractor force me to build strings like that?!

Er… it doesn't.

It turns out that I am as guilty as anyone else in finding a solution when scrambling to meet a deadline. And I am just as guilty here in never bothering to check the documentation which is perfectly clear. At any rate, I can clean that code up a bit with:
  it('updates value when internal state changes', function() {
    var selector = 'x-pizza';

    browser.executeScript(function(selector){
      var el = document.querySelector(selector);
      var options = el.shadowRoot.querySelectorAll("#firstHalf option");
      options[1].selected = true;

      var e = document.createEvent("Event");
      e.initEvent("change", true, true);
      options[1].dispatchEvent(e);

      button = el.shadowRoot.querySelector("#firstHalf button");
      button.click();
    }, [selector]);

    expect($(selector).getAttribute('value')).
      toMatch('pepperoni');
  });
That is still not pretty, but the ugly is down by an order of magnitude. It is a little annoying supplying the "x-pizza" selector in the list of arguments at the end of the executeScript(), but the real ugly remains in the form of that createEvent() inside the executeScript() that triggers a Polymer-required event.

It sure would be nice if I could click() the <select>, then <click> the correct <option>. Alas, this is WebDriver shadow DOM limitation in action. If I grab the <select> from executeScript(), then try to click it:
  it('updates value when internal state changes', function() {
    var selector = 'x-pizza';
    var toppings = browser.executeScript(function(selector){
      var el = document.querySelector(selector);
      return el.shadowRoot.querySelector('#firstHalf select');
    }, [selector]);

    toppings.then(function(toppings){
      toppings.click();
    });
    // ...
  });
I get ye olde stale element error:
1) <x-pizza> updates value when internal state changes
   Message:
     StaleElementReferenceError: stale element reference: element is not attached to the page document
  (Session info: chrome=39.0.2171.95)
  (Driver info: chromedriver=2.12.301324 (de8ab311bc9374d0ade71f7c167bad61848c7c48),platform=Linux 3.13.0-37-generic x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:02:37'
System info: host: 'serenity', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-37-generic', java.version: '1.7.0_65'
Session ID: c91503b6a80a9931478f6908f80f16d4
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=LINUX, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=/tmp/.com.google.Chrome.Dfu9DJ}, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=39.0.2171.95, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, applicationCacheEnabled=false, takesScreenshot=true}]
The usual state element fixes have no effect since this element is still attached—but attached in the unreachable (for WebDriver) shadow DOM.

So I am stuck with the ugly. Or am I?

Page Objects to the rescue:
  it('updates value when internal state changes', function() {
    new XPizzaComponent().
      addFirstHalfTopping('pepperoni');

    expect($('x-pizza').getAttribute('value')).
      toMatch('pepperoni');
  });
To make that work, I need to define the object in the Protractor onPrepare(), which resides in the configuration file. First, I need to add the object to Protractor's global namespace:
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['tests/XPizzaSpec.js'],
  onPrepare: function() {
    browser.ignoreSynchronization = true;

    global.XPizzaComponent = XPizzaComponent;
    function XPizzaComponent() {
      this.selector = 'x-pizza';
    }
  }
};
Then I only need to define the addFirstHalfTopping() method, which mostly comes from the "ugly" test code:
    XPizzaComponent.prototype = {
      addFirstHalfTopping: function(topping) {
        browser.executeScript(function(selector, v){
          var el = document.querySelector(selector);

          var select = el.$.firstHalf.querySelector("select"),
              button = el.$.firstHalf.querySelector("button");

          var index = -1;
          for (var i=0; i<select.length; i++) {
            if (select.options[i].value == v) index = i;
          }
          select.selectedIndex = index;

          var event = document.createEvent('Event');
          event.initEvent('change', true, true);
          select.dispatchEvent(event);

          button.click();
        }, this.selector, topping);
      }
    };
Since I "hide" this ugly in a page object, I have less compunction over using Polymer properties or methods. In this case, I use the dollar sign property to get the container element with the ID of firstHalf.

In the end, this is very similar to the page object work that I did in Karma. Only now I can rely on Protractor's promises to wait for the element's value property to be present instead of the async() callback craziness that was required for Karma. That is an exciting win.

Now the ugly, at least what is left of it, all resides in the Page Object defined in the configuration. I can definitely live with that. More than that—I may be starting to like Protractor as a Polymer testing solution.


Day #29

Saturday, August 9, 2014

Testing Paper (JavaScript Polymer)


My tests fail. That is hardly cause for concern—I did just switch my <x-pizza> Polymer element from a single display of a bunch of drop-down elements to a Paper-based tabs approach. And, since I am using Page Objects to wrap interaction with my custom element, this should be an easy fix.

“Should.”

Tests fail with messages like:
Expected '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":[]}'
to equal '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["green peppers"]}'.
That hardly seems a problem—my page object no longer knows how to add toppings. It had been taught to add toppings with the old drop down lists:



Now I need to teach the page object how to choose the appropriate tab and choose the corresponding ingredient from last night's Paper interface:



To fix this, I should only have to change the addWholeTopping() call in the Jasmine test setup:
  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()).
        toEqual(with_toppings);
    });
  });
The end result should be the same: the JSON representation should have green peppers on the entire pizza.

When interacting with this on the page, I have to click the tab, then click the green peppers from the pizza ingredients list. In Jasmine + Polymer + Page Objects parlance, that should look something like:
XPizzaComponent.prototype = {
  // ...
  addWholeTopping: function(v, cb) {
    // Click the tab:
    this.el.$.whole_tab.click();

    // Click green peppers in the active pizza toppings element:
    this.el.shadowRoot.
      querySelector('x-pizza-toppings[active]').
      $.green_peppers.
      click();

    return this.flush(cb);
  }
  // ...
};
Except this still fails. It fails, but I have succeeded in changing the error message. So, I am probably on the right track. The failure now includes green peppers in the result, but on the first half, not the entire pizza:
Chrome 36.0.1985 (Linux) <x-pizza> adding a whole topping updates the pizza state accordingly FAILED
        Expected '{"firstHalfToppings":["green peppers"],"secondHalfToppings":[],"wholeToppings":[]}'
        to equal '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":["green peppers"]}'.
My first thought here is that I am not giving the tab click time enough to complete such that the whole toppings element is active. If that is the case, then clicking green peppers on the currently active tab would add from the first half toppings since it is active by default. That seems a perfectly reasonable explanation. So of course it is wrong.

Even if I add absurd amounts of delay before clicking green peppers in the active toppings selector, the error message does not change. So the problem must lie elsewhere. After some trial and error, I eventually find the problem: clicking the whole toppings tab is broken.

Well, not so much broken as incorrect. It turns out that Paper / Core Polymer elements tend to use mouse up/down events rather than click events. So I have to replace the nice, clean click() call with messy initEvents calls:
  addWholeTopping: function(v, cb) {
    // Click the tab:
    var evt1 = document.createEvent("MouseEvents");
    evt1.initEvent("mousedown", true, true);
    this.el.$.whole_tab.dispatchEvent(evt1);

    var evt2 = document.createEvent("MouseEvents");
    evt2.initEvent("mouseup", true, true);
    this.el.$.whole_tab.dispatchEvent(evt2);

    // Click green peppers in the active pizza toppings element:
    this.el.shadowRoot.
      querySelector('x-pizza-toppings[active]').
      $.green_peppers.
      click();

    return this.flush(cb);
  }
With that, I… still get the same exact failure. The green peppers are still being added to the first half. It turns out that a slight delay is needed after all to allow the selected tag to change the current page. This only requires a single event loop, so I setTimeout() for zero milliseconds:
  addWholeTopping: function(v, cb) {
    // Click the tab:
    var evt1 = document.createEvent("MouseEvents");
    evt1.initEvent("mousedown", true, true);
    this.el.$.whole_tab.dispatchEvent(evt1);

    var evt2 = document.createEvent("MouseEvents");
    evt2.initEvent("mouseup", true, true);
    this.el.$.whole_tab.dispatchEvent(evt2);

    // Click green peppers in the active pizza toppings element:
    var that = this;
    setTimeout(
      function(){
        that.el.shadowRoot.
          querySelector('x-pizza-toppings[active]').
          $.green_peppers.
          click();

        return that.flush(cb);
      },
      0
    );
  },
With that, I have my test passing.

(The flush() call at the end of that method works with Polymer's async() and Jasmine's done() to ensure proper timing of tests with this element.)

I greatly appreciate making no changes to the actual test code. It still reads exactly as it did when I started. I only needed to change the addWholeTopping() method to accommodate changes to that area of my Polymer element. This feels like a nice win. I would much rather send a simple click message to my Polymer elements, but I can live with the mouse events now that I know about them.


Day #147

Friday, August 1, 2014

Page Objects Testing Still Viable with Polymer


Well, it was pretty easy to upgrade the Dart version of my Page Objects testing code. What about the JavaScript version?

Both the Dart and JavaScript versions are 2 months old—2 whole months! Everything must be broken by now, right? It turned out that, despite numerous changes to Polymer.dart in the interim, very little needed to change to get the tests passing—and most of that was due to my adopting a pre-release version of Polymer.dart that was ultimately abandoned. So hopefully the JavaScript version of the code will be just as easy.

I am using the Page Object testing pattern, but the actual tests are performed with Karma and Jasmine. Since I have yet to update anything, it still works fine:
$ karma start
INFO [karma]: Karma v0.12.1 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Linux)]: Connected on socket fGH6ETvI7bhvtg90F-ge with id 84692123
Chrome 36.0.1985 (Linux): Executed 2 of 2 SUCCESS (0.159 secs / 0.126 secs)
Let's see if I can break it.

I am installing and maintaining the Polymer library with Bower. It's been 2 months, so no doubt there is a new best practice for this sort of thing, but I'll stick with it for now. My bower.json simply points to any version of Polymer:
{
  "name": "page_objects",
  // ...
  "dependencies": {
    "polymer": "Polymer/polymer",
    "angular-mocks": "~1.2.16"
  }
}
I have no idea why I have angular-mocks listed as a dependency in there. According to bower ls it is not installed so I remove it. Speaking of bower ls, it reports plenty of shiny updates:
$ bower ls
page_objects#0.0.0 /home/chris/repos/polymer-book/book/code-js/page_objects
└─┬ polymer#0.2.2 (0.3.4 available)
  ├─┬ core-component-page#0.2.2 (latest is 0.3.4)
  │ ├── core-action-icons#0.2.2 (latest is 0.2.4)
  │ ├── platform#0.2.2
  │ └── polymer-ui-action-icons#0.2.2 (latest is 0.3.0)
  └── platform#0.2.2 (latest is 0.3.4)
Desirous of the promise of shiny new, I bower update:
$ bower update
...
polymer#0.3.4 bower_components/polymer
├── core-component-page#0.3.4
└── platform#0.3.4

core-component-page#0.3.4 bower_components/core-component-page
├── platform#0.3.4
└── polymer#0.3.4

platform#0.3.4 bower_components/platform
And… my tests still run! And as an added bonus, they still pass:
$ karma start
INFO [karma]: Karma v0.12.1 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Linux)]: Connected on socket gh74mOQPT1Npy4xGt31j with id 25071706
Chrome 36.0.1985 (Linux): Executed 2 of 2 SUCCESS (0.187 secs / 0.152 secs)
If I were only doing this for an application, I might leave well enough alone. But, since this is for a book (Patterns in Polymer—buy it today!), I need to keep both code library and testing library as up-to-date as possible.

Now bear with me here… the code library is installed with a package manager as is the testing framework. But, even though they are both written in JavaScript, I need to use two different package managers to install them. Again it's been 2 months so the best of class for both package managers has probably changed, but I need to use both package managers. Unless that's changed too.

That reminds me of a joke:



But seriously, JavaScript is awesome. The package manage that is managing the testing framework is npm. Naturally, it has its own package file, package.json, which looks like this currently:
{
  "name": "page_objects",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "karma-jasmine": "~0.2.0",
    "karma-chrome-launcher": ">0.0"
  }
}
And, unless I am mistaken, this is already the latest version of karma-jasmine. Has this really not been updated since April? That seems scary. The underlying Jasmine project has a new (minor) revision and has had dozens of changes since the last karma-jasmine update. It may be time to adopt Mocha as the current testing library best practice. I will leave that until tomorrow.

All that's left tonight is to fire it up in the browser and check for problems—of which I find none. I can add toppings, which show up as JSON inside a <pre> tag:



Cool! There aren't even any console messages. Both my Page Objects testing approach and the (admittedly simple) Polymer element still work perfectly two months down the line. I call it a night here. Up tomorrow: Mocha.


Day #140

Thursday, July 31, 2014

Working Tests Again on Polymer.dart 0.12


Time to get back to Patterns in Polymer. It has been two months since the last release of the book and the last real changes to the code. So no doubt everything is broken.

Not that I'm complaining. I signed on for this when I started a book on a technology that was quite up front about being in the the pre-alpha stages. Truth be told, that is part of the fun!. So let's see what broke. The quickest way to figure this out is tests, so I start with the testing with Page Objects chapter. To ease my way back in, I start with the Dart version of the code.

After clearing up a spurious curly brace (seriously, how did I manage to commit code with an extra curly brace in it?), I make sure that my tests pass against the old version of Polymer (and Dart):
$ ./test/run.sh
CONSOLE WARNING: ShadowRoot.resetStyleInheritance and ShadowRoot.applyAuthorStyles now deprecated in dart:html.
Please remove them from your code.

CONSOLE MESSAGE: PASS: [defaults] it has no toppings
CONSOLE MESSAGE: PASS: [adding toppings] updates the pizza state accordingly
CONSOLE MESSAGE:
CONSOLE MESSAGE: All 2 tests passed.
I am none too surprised that applyAuthorStyles is deprecated (though I'm a little sad that I left it in there). That aside, everything appears to be in order. So let's change that.

I start a pub upgrade:
$ pub upgrade
Resolving dependencies... (4.9s)
...
> polymer 0.12.0 (was 0.10.0-pre.9) (1 newer version available)
> polymer_expressions 0.12.0 (was 0.10.0-pre.1)
...
> web_components 0.5.0 (was 0.3.3)
...
Changed 30 dependencies!
That is sure to break all kinds of things. And sure enough, my test suite fails to even start.

Fortunately, I have not been completely away from Polymer in the intervening time. James Hurford and I went through this pain when we updated the <ice-code-editor> element (from ICE Code Editor). From that experience, I rework the test context page to load the Polymer platform JavaScript source (previously it was Dart):
<head>
  <!-- Load Polymer -->
  <script src="packages/web_components/platform.js"></script>

  <!-- Load component(s) -->
  <link rel="import" href="packages/page_objects/elements/x-pizza.html">

  <!-- The actual tests -->
  <script type="application/dart" src="test.dart"></script>
  <script src="packages/unittest/test_controller.js"></script>
</head>
This code was built on an experimental version of Polymer.dart, so I also have to remove some mime-type tomfoolery. I also have to reintroduce a initPolymer() call to the test's main() entry point:
// ...
main() {
  initPolymer();
  // Actual tests go here...
}
Even with that, I was still getting a rather unhelpful error when I attempted to run the tests:
CONSOLE WARNING: line 213: FAIL
CONSOLE ERROR: Exception: NoSuchMethodError: method not found: 'whenPolymerReady'
Receiver: Instance of 'JsFunction'
Arguments: [Closure: () => dynamic]
This turns out to also be caused by a jump from a pre-release version of Polymer.dart to 0.12. The fix for this was to simply import Polymer into the top-level Polymer element definition (I am testing <x-pizza>):
<link rel="import" href="../../../packages/polymer/polymer.html">
<link rel="import" href="x-pizza-toppings.html">
<polymer-element name="x-pizza">
  <template>
    <!-- ... -->
  </template>
  <script type="application/dart" src="x_pizza.dart"></script>
</polymer-element>
With that, I have my tests passing again:
$ ./test/run.sh
...
CONSOLE WARNING: line 12: flushing %s elements
CONSOLE MESSAGE: unittest-suite-wait-for-done
CONSOLE MESSAGE: PASS: [defaults] it has no toppings
CONSOLE MESSAGE: PASS: [adding toppings] updates the pizza state accordingly
CONSOLE MESSAGE:
CONSOLE MESSAGE: All 2 tests passed.
I will worry about that “flushing %s elements” another time. For now, I am satisfied to have my tests passing.

I also find that I need to update the actual page that demonstrates this Polymer element. As in the test, I need to load the web components polyfill JavaScript code. I also have to initPolymer(), which is done under normal circumstances with the built-in init.dart:
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Load platform polyfills -->
    <script src="packages/web_components/platform.js"></script>

    <!-- Load component(s) -->
    <link rel="import"
          href="packages/page_objects/elements/x-pizza.html">

    <!-- Start Polymer -->
    <script type="application/dart">
      export 'package:polymer/init.dart';
    </script>
  </head>
  <body>
    <div class="container">
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <x-pizza></x-pizza>
    </div>
  </body>
</html>
With that, I have it working again in both Dart and JavaScript (the latter courtesy of Polymer.dart's built-in dart2js transformer:



I am back in business! No doubt I have other clean-up to do and some associated rewriting. And of course, screencasts for readers of the “Extras” version of Patterns in Polymer. For today, it is good to be back.


Day #139

Monday, March 24, 2014

Worky Scheduled Polymer Page Objects


Testing semi-complex Polymer.dart elements certainly has proved troublesome.

I am still working on my <x-pizza> pizza builder. The UI is not terribly complex:



The semi-complexity comes from the makeup of the Polymer element's <template>, which pulls in locally defined <x-pizza-toppings> sub-components:
<link rel="import" href="x-pizza-toppings.html">
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre id="state">{{pizzaState}}</pre>
    <x-pizza-toppings id="firstHalfToppings"
                      name="First Half Toppings"
                      ingredients="{{ingredients}}"></x-pizza-toppings>
    <x-pizza-toppings id="secondHalfToppings"
                      name="Second Half Toppings"
                      ingredients="{{ingredients}}"></x-pizza-toppings>
    <x-pizza-toppings id="wholeToppings"
                      name="Whole Toppings"
                      ingredients="{{ingredients}}"></x-pizza-toppings>
    <p class=help-block>
      Build Your Pizza!
    </p>
  </template>
  <script type="application/dart" src="x_pizza.dart"></script>
</polymer-element>
This is not too complex—just complicated enough to warrant the “semi-complex” label. And to give me fits testing.

Most of my fits are due to the asynchronous nature of Polymer elements—especially when sub-components come into play. I had hoped that relying on scheduled_test, which is a unittest replacement with nice asynchronous support, might solve my problems. But no.

James Hurford was kind enough to give me a hint about readying Polymer elements for testing. He suggested that, after the element was created:
  setUp((){
    schedule((){
      _el = createElement('<x-pizza></x-pizza>');
      document.body.append(_el);

      xPizza = new XPizzaComponent(_el);
    });
    // ...
  });
That I could schedule an async call which would fire after updating the UI. That seems like it might be right up my alley:
  setUp((){
    schedule((){ /* Create element... */ });

    schedule((){
      var _completer = new Completer();
      _el.async((_)=> _completer.complete());
      return _completer.future;
    });
  });
That actually helps quite a bit, but it does not solve all of my problems. It really seems as though Polymer is extremely sensitive to timing. I had accidentally left a delay in the my setup:
  setUp((){
    schedule((){ /* Create element... */ });

    schedule((){
      var _completer = new Completer();
      _el.async((_)=> _completer.complete());
      return _completer.future;
    });

    schedule(()=> new Future.delayed(new Duration(milliseconds: 750)));
  });
When removed, everything started working. I have no idea why that delay would prevent my tests from seeing changes in the Polymer, but that is how the failures would manifest—the original values would show rather than updates in response to page updates.

I also performed a bit of code cleanup in the Polymer code itself. Specifically, I found it best to listen for events in the enteredView() (will eventually be renamed attached()) callback:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizza.created(): super.created();
  enteredView() {
    super.enteredView();

    on['topping-change'].listen((_){
      updatePizzaState();
    });
    updatePizzaState();
  }
  // ...
}
That code had been in the created() constructor, but it seemed more robust in enteredView(). Specifically, it worked with multiple elements and tests without random failures.

So it took a bit (and much thanks to James for the tip), but I finally have a robust test suite for this Polymer element.


Day #13

Sunday, March 23, 2014

Scheduled Polymer Page Objects Tests


Page Objects for testing Polymer seem to be working out for me nicely. What's not working out so well for me is asynchronous testing—with either the Dart or JavaScript versions of Polymer.

If anything, testing is a little easier in JavaScript, thanks to Jasmine's asynchronous helpers like wait() and run(). As odd as it may seem, I am struggling more with Dart testing than JavaScript testing. Thankfully, the fine Dart folks maintain scheduled_test for asynchronous testing in Dart. Let's see if that make my life any easier when testing Polymer code.

I start by switching my development dependencies from vanilla unittest to scheduled_test in my projects pubspec.yaml:
name: model_example
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
A quick pub update and I am ready:
➜  dart git:(master) ✗ pub update
Resolving dependencies.....................
...
Downloading scheduled_test 0.10.1...
...
Changed 2 dependencies!
The resulting tests are much cleaner. That is not too surprising given my experience in the past with scheduled_test. For instance, adding a whole topping to my <x-pizza> pizza builder element is now just a series of schedules:
  group("[adding toppings]", (){
    test('updates the pizza state accordingly', (){
      var toppings = JSON.encode({
        'firstHalfToppings': [],
        'secondHalfToppings': [],
        'wholeToppings': ['green peppers']
      });

      schedule(()=> new Future.delayed(new Duration(milliseconds: 150)));

      schedule(()=> xPizza.addWholeTopping('green peppers'));

      schedule(()=> new Future.delayed(new Duration(milliseconds: 1500)));

      schedule((){
        expect(
          xPizza.currentPizzaStateDisplay,
          equals(toppings)
        );
      });
    });
  });
Some of those schedules are delays to allow the Polymer platform to do its thing. Others are the Page Objects interaction or interrogation.

But as nice as this is to read, it is not working any better for me. If anything, things are worse. No matter what delays I try, I am still getting test failures. Worse, the test failures seem to be more consistent. With the non-scheduled_test tests, I could reliably get the tests to pass under content_shell, even if they usually failed in Dartium. With scheduled_test, I now reliably get failures in both content_shell and Dartium.

Bother. I suspect my tests are trying to tell me something—especially now that I am (hopefully) being more strict with the order in which test code is evaluated. But I'll be darned if I can figure out what my tests are saying. Stumped, I call it a night here, but I think I need to give this another go tomorrow.


Day #12

Friday, March 21, 2014

Polymer Page Objects in Dart


I remain skeptical that Page Objects are a good idea for long term maintenance of a test suite. But after last night, they sure seem like they can come in handy.

So tonight, I give them a try in my Dart test suite for a simple <x-pizza> Polymer element:



I start a new test.dart with a Page Object wrapper for <x-pizza> elements. To begin with, I only need a getter that extracts the current pizza state from a pre#state element inside the Polymer element:
class XPizzaComponent {
  PolymerElement el;
  XPizzaComponent(this.el);
  String get currentPizzaStateDisplay => el.$['state'].text;
}
Then, I do the usual Polymer.dart test setup, calling initPolymer(), adding my <x-pizza> element to the test page, and finally creating a Page Objects instance:
main() {
  initPolymer();

  PolymerElement _el;
  XPizzaComponent xPizza;

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

    xPizza = new XPizzaComponent(_el);
  });
  // ...
}
With that, I can write my first Page Object test as:
  group("[defaults]", (){
    test('it has no toppings', (){
      var no_toppings = JSON.encode({
        'firstHalfToppings': [],
        'secondHalfToppings': [],
        'wholeToppings': []
      });

      expect(
        xPizza.currentPizzaStateDisplay,
        no_toppings
      );
    });
  });
That fails because this is an older version of the Polymer element that is not JSON encoding the pizza state:
CONSOLE MESSAGE: FAIL: [defaults] it has no toppigns
  Expected: '{"firstHalfToppings":[],"secondHalfToppings":[],"wholeToppings":[]}'
    Actual: 'First Half: []
'   
    'Second Half: []
'   
To get the test passing, I update my Polymer class to properly JSON encode the pizza state:
import 'package:polymer/polymer.dart';
import 'dart:convert';

@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  Pizza model;
  @observable String pizzaState;

  XPizza.created(): super.created() {
    // ...
    updatePizzaState();
  }

  updatePizzaState([_]) {
    pizzaState = JSON.encode({
      'firstHalfToppings': model.firstHalfToppings,
      'secondHalfToppings': model.secondHalfToppings,
      'wholeToppings': model.wholeToppings
    });
  }
  // ...
}
Now comes the fun part.

I need to be able to select items from the <select> list in my Polymer element. That was a pain in the JavaScript version of this element. Thankfully, the Page Object version of the addWholeTopping() method in Dart is pretty straight-forward. At least, it is straight-forward having the JavaScript version to reference. The Dart version is:
class XPizzaComponent {
  PolymerElement el;
  XPizzaComponent(this.el);
  String get currentPizzaStateDisplay => el.$['state'].text;
  XPizzaComponent addWholeTopping(String topping) {
    var toppings = el.$['wholeToppings'],
        select = toppings.query('select'),
        button = toppings.query('button');

    var index = -1;
    for (var i=0; i<select.length; i++) {
      if (select.options[i].value == topping) index = i;
    }
    select.selectedIndex = index;

    var event = new Event.eventType('Event', 'change');
    select.dispatchEvent(event);

    button.click();

    return this;
  }
}
That is more or less copied-and-pasted from the JavaScript version of the Page Object. As in JavaScript, I find that I have to dispatch a change event to the <select> element. That aside, this method is straight procedural code selecting an item and clicking a button.

Armed with that, I can write the next test as:
  group("[adding toppings]", (){
    setUp((){
      var _completer = new Completer();
      Timer.run(_completer.complete);
      return _completer.future;
    });

    test('updates the pizza state accordingly', (){
      xPizza.addWholeTopping('green peppers');

      var toppings = JSON.encode({
        'firstHalfToppings': [],
        'secondHalfToppings': [],
        'wholeToppings': ['green peppers']
      });

      new Timer(
        new Duration(milliseconds: 100),
        expectAsync((){
          expect(
            xPizza.currentPizzaStateDisplay,
            toppings
          );
        })
      );
    });
  });
As I found in the JavaScript version of the tests, I have to introduce some minor time delays to allow the Polymer element to draw or update itself. But with carefully placed Timer runs, I have a second passing test:
PASS: [defaults] it has no toppings
PASS: [adding toppings] updates the pizza state accordingly
Those Timer delays are a little on the ugly side, but Page Objects again play very well with testing my Polymer element. There may be something to these Page Object things after all.


Day #10

Thursday, March 20, 2014

Testing Polymers with Page Objects (which I hate)


I hate everything about Page Objects. So surely I can be an impartial evaluator at applying them to testing Polymer, right?

OK, I don't hate everything about Page Objects. I loathe code reuse and indirection in tests. I am a testing fiend, but would rather let my code go untested than introduce indirection into my tests. I cannot count the number of hours that I have traced through other coder's helpers, behaves-likes, and attempts at DRYing up tests. I am decidedly of the opinion that test code should be un-DRY, procedural and entirely contained in the test or associated setup block. Simply put, debugging test helpers drives me absolutely nuts.

So why even consider Page Objects, which expose page- or component-level interaction methods? Mostly because I wound up introducing a helper for selecting items from a Polymer element's <select> last night:
  describe('adding a whole topping', function(){
    it('updates the pizza state accordingly', function(){
      var toppings = el.$.wholeToppings,
          select = toppings.$.ingredients,
          button = toppings.$.add;

      helpers.selectOption(select, 'green peppers');
      button.click();
      // The expectations are set later...
    });
  });
I need that helper because Polymer elements need actual native events to trigger bound variable updates:
var helpers = {
  selectOption: function(el, v) {
    var index = -1;
    for (var i=0; i<el.length; i++) {
      if (el.options[i].value == v) index = i;
    }
    el.selectedIndex = index;
    var event = document.createEvent('Event');
    event.initEvent('change', true, true);
    el.dispatchEvent(event);
  }
};
That code was sufficiently ugly enough to compel me, an test indirection hater, to introduce indirection into my test. And really, how much worse could Page Objects be?

I think it makes sense to leave the Polymer element creation to the test setup, so I define the Page Object constructor as accepting the element in question:
function XPizzaComponent(el) {
  this.el = el;
}
So the setup code is then responsible for adding the necessary <x-pizza> element (which builds custom pizzas) to the page for testing and then instantiating the XPizzaComponent object:
describe('', function(){
  var container, xPizza;

  beforeEach(function(){
    container = document.createElement("div");
    var el = document.createElement("x-pizza");
    container.appendChild(el);
    document.body.appendChild(container);

    xPizza = new XPizzaComponent(el);
    // Additional setup...
  });
  
  // Tests here...
});
Next, I need to define methods for my Page Object that return current information about the element and represent different ways that a user might interact with the element. Of late, I have been adding whole toppings to the pizza:
function XPizzaComponent(el) {
  this.el = el;
}
XPizzaComponent.prototype = {
  addWholeTopping: function(v) {
    var toppings = this.el.$.wholeToppings,
        select = toppings.$.ingredients,
        button = toppings.$.add;

    var index = -1;
    for (var i=0; i<select.length; i++) {
      if (select.options[i].value == v) index = i;
    }
    select.selectedIndex = index;
    var event = document.createEvent('Event');
    event.initEvent('change', true, true);
    select.dispatchEvent(event);

    button.click();

    return this;
  }
};
That is a less generalized version of last night's helpers.selectOption(). It may be less generalized, but it is far more meaningful in the context of my page / web component. Also YAGNI.

In addition to representing how a user interacts with my Polymer element, I also need to expose methods that can interrogate the element for current state. Of late, I have been working to test the current display state of the pizza, which is a JSON bound variable inside a <pre> tag. So I add a method for that as well to my Page Object:
function XPizzaComponent(el) {
  this.el = el;
}
XPizzaComponent.prototype = {
  addWholeTopping: function(v) { /* ... */ },
  currentPizzaStateDisplay: function() {
    if (this.el.$ === undefined) return '';
    return this.el.$.state.textContent;
  }
};
With that, and with my setup already instantiating this XPizzaComponent Page Object as xPizza, I can rewrite my tests as:
  describe('defaults', function(){
    it('has no toppings anywhere', function() {
      var no_toppings = JSON.stringify({
        firstHalfToppings: [],
        secondHalfToppings: [],
        wholeToppings: []
      });

      expect(xPizza.currentPizzaStateDisplay()).
        toEqual(no_toppings);
    });
  });
I grudgingly admit that this is fairly nice.

I am unsure how best to handle asynchronous code with this approach. The bound variable is not updated immediately after a user selects it from the drop-down. Rather, the browser needs to run through an event loop before Polymer updates bound variables. For now, I leave that in the hands of my tests rather than trying to force it into the Page Object:
  describe('adding a whole topping', function(){
    it('updates the pizza state accordingly', function(){
      xPizza.addWholeTopping('green peppers');

      // Wait a single event loop to allow Polymer to update the element…
      waits(0);
      runs(function(){
        var with_toppings = JSON.stringify({
          firstHalfToppings: [],
          secondHalfToppings: [],
          wholeToppings: ['green peppers']
        });

        expect(xPizza.currentPizzaStateDisplay()).
          toEqual(with_toppings);
      });
    });
  });
That aside, I again grudgingly admit that adding a topping and interrogating the display state are nicer with Page Objects. Darn it.

There may be something to this approach after all. But if anyone tries to clean up my addWholeToppings() method or factor any of this out into a separate library, there's gonna be trouble. Trouble I say!


Day #9