3

We have several situations where our Polymer elements have methods that rely on global behaviour, such as viewport size detection, or an analytics package that injects a global variable.

Now I'm trying to test these methods using Web Component Tester, but I can't see how to inject e.g. stubs into the window object (e.g. like is possible with webdriver's execute function). How do I do this?

An example of a test that didn't work:

    test('my-element should not crash when `Analytics` is blocked', function () {
        // I'd like window.Analytics in my app to be undefined,
        // but this doesn't work, obviously:
        window.Analytics = undefined;

        myEl = fixture('my-element');
        expect(myEl.ready).to.not.throw();
    });
Vincent
  • 4,876
  • 3
  • 44
  • 55

1 Answers1

0

You could try using before or beforeEach and after or afterEach hooks.

  var tempAnalytics = window.Analytics;
  before(function() { 
   // runs before all tests in this block
   window.Analytics = undefined;
  });

  after(function() {
    // runs after all tests in this block
    window.Analytics = tempAnalytics;
  });

Another option is to use Sinon sandboxes to stub the property.

var sandbox = sinon.sandbox.create();
sandbox.stub(window, "Analytics", undefined);

// then restore when finished like above
sandbox.restore();
Gordon
  • 4,823
  • 4
  • 38
  • 55
  • But that's still on the `window` object _inside my tests_, while I want to access the one available to my app. So something like webdriver's [execute](http://webdriver.io/api/protocol/execute.html), but for Web Component Tester. – Vincent Dec 14 '16 at 19:19
  • Would need a bit more info in your example. Generally the tests would just be for the function you want to test. If there are other functions beyond the scope of the function you can stub their behaviour. – Gordon Dec 15 '16 at 08:07
  • Hi Gordon, check if in you component there are something like: let Analytics = window.Analytics ; if you have it means you are keeping a reference and cleaning the window reference will be too late. – Adriano Spadoni May 22 '17 at 08:49