Search code examples
javascriptpolymerweb-component-tester

How do you test elements that require the light dom to be loaded?


I have an element:

<dom-module id="ens-page-router">

    <template>

        <iron-pages attr-for-selected="url">
            <content select="ens-page"></content>
        </iron-pages>

    </template>

    <script>
        Polymer({
            is: 'ens-page-router',
            attached: function(){
                //using async because the pages url will be undefined otherwise
                this.async(function(){           
                    var pages = this.getContentChildren()
                    var ironPages = this.$$('iron-pages');


                    pages.forEach(function(elem){
                        page(elem.url, function(){
                            ironPages.select(elem.url);
                        });
                    });

                    page();
                });
            }
        });
    </script>

</dom-module>

and a test-fixture:

<test-fixture id='underTest'>
        <template>
            <ens-page-router>
                <ens-page url="/derp">
                    <div>derp</div>
                </ens-page>
                <ens-page url="/foo/bar">
                    <div>foo bar</div>
                </ens-page>
            </ens-page-router>
        </template>    
    </test-fixture>

I'm not sure how to run my test after the light dom has been initialized. I've tried listening to the attached event but it never fires, as I have no way to register before calling fixture(). I've also tried testing synchronously but the test runs before the attached event is fired.

 describe("<ens-page-router>", function(){
        var underTest;
        var ironPages;
        var selectSpy;
        var routes = {};

        //stub page.js
        var fakePage = function(path, callback){
            if(callback){
                routes[path] = callback;
            }else if(path){
                routes[path]();
            }

        beforeEach(function(){
            page = fakePage;
            underTest = fixture('underTest');
            ironPages = underTest.$$('iron-pages');
            selectSpy = sinon.spy(ironPages, "select");
        });

        it('should select the derp page', function(){
            page('/derp');

            assert(selectSpy.calledWith("/derp"));
        });
 });

Solution

  • Wrapping the test in a setTimeout will allow the dom to be loaded.

     it('should select derp as the current page', function(done){       
                waitForDom(function(){
                    page('/derp');
    
                    assert(selectSpy.calledWith("/derp"));
                    done();
                });
            });
    
    function waitForDom(callback){
                setTimeout(callback, 1);
            }