Search code examples
polymerpolymer-1.0sinonweb-component-tester

Can not stub private element in WCT


Using Polymer 1 and Web component tester... testing in shady dom on chrome.

In WCT, trying to stub spToast.display() with stub('sp-toast', { display: ()=> {} }); but I get error with Attempted to wrap undefined property display as function.... what I am doing wrong?

The reason why I am trying to stub it is because I get spToast.display is not a function when the test runs the code base.

original code:

 showAgeWarning: function() {
    var spApp = Polymer.dom(document).querySelector('sp-app');
    var spToast = Polymer.dom(spApp.root).querySelector('sp-toast');

    var msg = "foo"
    spToast.display('information', msg);
  },

test code:

<test-fixture id="sp-veteran">
  <template>
    <h2>edit veteran</h2>
    <sp-app>
      <sp-toast></sp-toast>
      <sp-veteran>
      </sp-veteran>
    </sp-app>
  </template>
</test-fixture>

    setup(function() {
      replace('sp-app').with('fake-sp-app');
      replace('sp-ajax').with('fake-sp-ajax');
      stub('sp-value-dropdown', { setInvalidState: (state)=> {} });
      myEl = fixture('sp-veteran');
    });

  test('it should validate the veteran', function() {
      var spApp = Polymer.dom(myEl.root).querySelector('sp-app');
      var spToast = Polymer.dom(spApp.root).querySelector('sp-toast');
      sinon.stub(spToast, 'display');

Solution

  • When you get Attempted to wrap undefined property display as function it means that it can't replace a method that doesn't exist (yet).

    If you actually get a value for var spToast = Polymer.dom(spApp.root).querySelector('sp-toast') in your test, and nothing about your test is going to give display a value, you could just set it, a la spToast.display = function() {}; then you should be able to set a spy on it or what have you as needed.

    Put it all together and you could have

    test('it should validate the veteran', function() {
          var spApp = Polymer.dom(myEl.root).querySelector('sp-app');
          var spToast = Polymer.dom(spApp.root).querySelector('sp-toast');
          spToast.display = function() {};
          sinon.spy(spToast, 'display');
          // Trigger the side effect that would lead to `display` being called
          assert.equal(
            spToast.display.calledOnces,
            true
          );
    });