Search code examples
polymereslintpolymer-2.xweb-component-tester

ESLint no-undef on imported element class


I have an element (display-enter-button.html) that I want to test:

<template>
    <data-local-storage id="localStorage"></data-local-storage>
    <app-location route="{{route}}"></app-location>
    <span role="button" tabindex="0" class="btn" on-click="_btnClick" on-KeyPress="_btnKeyPress">enter here</span>
</template>

<script>
    class DisplayEnterButton extends Polymer.Element {
        _btnClick() {
            // Something happens
        });
    }
</script>

I want to verify that the _btnClick method gets called when I click on the enter button. This is my unit test:

<head>
 <title>display-enter-button</title>
<script src="../../bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="../../bower_components/web-component-tester/browser.js"></script>
<!--
    Load component to test
-->
<link rel="import" href="../../src/displays/display-enter-button.html">
</head>
<body>
<!--
    Add component to test fixure and give it an incrementing id
-->
<test-fixture id="fixture-one">
    <template>
        <display-enter-button></display-enter-button>
    </template>
</test-fixture>

<script>
// Name the suite the same as the type of tests
suite('Query Selector Tests', function() {
    test('On click function called', function() {
        // Select element to trigger event
        var circle = fixture('fixture-one').shadowRoot.querySelector('.btn');
        // Spy on the method that should run
        var clickButton = sinon.spy(DisplayEnterButton.prototype, '_btnClick');
        // Trigger the event
        circle.click();
        // Test it
        sinon.assert.called(clickButton);
    });
});
</script>

The test runs, but I can't get past this ESLint error:

'DisplayEnterButton' is not defined no-undef

I'd like to avoid ESLint rule exceptions (such as global) if possible because I'm going to be using this pattern a lot in the future. How could I resolve this error?


Solution

  • An alternative to Xavier's solution that doesn't involve creating another instance of the test element is to fetch the actual element under test from the test fixture:

    <test-fixture id="BasicView">
      <template>
        <!-- give the test element an ID to query for it in tests -->
        <my-view1 id="testEl"></my-view1>
      </template>
    </test-fixture>
    
    <script>
      suite('my-view1 tests', function() {
        test('on click', function() {
          var proto = document.getElementById('testEl').constructor.prototype;
          var clickButton = sinon.spy(proto, '_btnClick');
          // ...
        });
      });
    </script>