mardi 8 août 2017

How to replace elements and stub methods in Polymer

In my unit tests, I would like to be able to replace elements with mocked elements and also provide stubs for methods of the original element.

For example, let's say the template of my component is like this:

<template>
   <my-other-element id="myOtherElement"></my-other-element>
</template>

Let's say later in my element I do something like this:

myMethod: function () {
   this.$.myOtherElement.foo();
}

When I write the unit test for my element, I would like to do the following:

  1. Mock the entire <my-other-element>
  2. Provide a stub method for foo()

I have found a way to achieve this but somehow it does not seem to be very clean. My current solution is the following:

var fooStub;

beforeEach(function () {
    fooStub = sinon.stub();

    replace('my-other-element').with('fake-my-other-element');
    document.createElement('fake-my-other-element').constructor.prototype = {
        foo: fooStub
    };
    element = fixture('basic');
});  

I am wondering if there is a better way to achieve the same results. Somehow creating an empty element in order to change the prototype property to add stubs does not seem to be the best way.

And I know you can also do this:

stub('my-other-element', {
    foo: fooStub
});

But I prefer to always mock everything in advance to make sure there are no side-effects coming from the child element.

Aucun commentaire:

Enregistrer un commentaire