Friday, October 3, 2014

Testing CSS Colors in Polymer


I have 5 whole tests covering the functionality of the Bootstrap styled Polymer element. And it is occurs to me that not a single one of those tests has anything to do with the intention of this chapter in Patterns in Polymer, which is styling Polymer elements.

The Polymer element in this case is a simple pricing plans element:



So it seems to me that I ought to be able to test that one of the individual pricing plans in the test is blue.

I have to fiddle with the setup, but I eventually get the following Jasmine test to work:
  describe('defaults', function(){
    var el;
    beforeEach(function(done){
      el = document.querySelector('pricing-plans');
      setTimeout(done, 10);
    });

    it('gets styles from external sources', function(){
      var primary_el = el.querySelectorAll('pricing-plan')[2],
          heading_el = primary_el.shadowRoot.querySelector('.panel-heading'),
          style = window.getComputedStyle(heading_el);

      expect(style.backgroundColor).toEqual('rgb(66, 139, 202)');
    });
  });
This finds the last <pricing-plan> element in my fixture file:
<pricing-plans>
<pricing-plan name="pricing plan 01">desc 01</pricing-plan>
<pricing-plan name="pricing plan 02">desc 02</pricing-plan>
<pricing-plan type="primary" name="pricing plan 03">desc 03</pricing-plan>
</pricing-plans>
The last element has the primary type set which Bootstrap will color blue by default. I had originally tried to grab the <pricing-plan> element directly to test, but found that I had to dive into that shadow DOM to grab the panel header to find the element that actually is blue.

The test then uses the getComputedStyle() method on window to find the background color of this element, which should be the specified shade of blue.

Among the tricks that I need to get this working is the setTimeout() dance in this test's setup—this gives the page time to load Bootstrap CSS and apply it (I am running this with Karma, so loading from a server does work). If I opt to use the apply-author-styles Polymer tag, I will also have to apply Bootstrap CSS to the main testing page. But, since this is just the @import solution for external CSS inside a Polymer element, this is all I need for tonight.

The end result is that the test passes:
...
SUCCESS  gets styles from external sources
Skipped 0 tests
And, more importantly, the test fails if I change the fixture from a panel-primary to a panel-success:
FAILED  gets styles from external sources
Expected 'rgb(223, 240, 216)' to equal 'rgb(66, 139, 202)'.
I was unsure how easy it would be to accomplish this, but testing computed CSS in Polymer elements turns out to be fairly clean and easy.


Day #202

No comments:

Post a Comment