1

我有一个要测试的元素(display-enter-button.html):

<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>

我想验证_btnClick当我点击回车按钮时该方法是否被调用。这是我的单元测试:

<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>

测试运行,但我无法通过这个 ESLint 错误:

'DisplayEnterButton' 未定义 no-undef

如果可能的话,我想避免 ESLint 规则异常(例如global),因为我将来会大量使用这种模式。我该如何解决这个错误?

4

2 回答 2

2

不涉及创建测试元素的另一个实例的 Xavier 解决方案的替代方法是从测试夹具中获取被测的实际元素:

<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>
于 2017-06-25T15:02:43.083 回答
1

编辑:托尼接受的答案是最好的解决方案

这也有效,但创建了一个新实例而不是使用夹具实例。

test('On click function called', function() {
        // Create instance of the class we want to test the methods of
        var proto = document.createElement('display-enter-button')
        .constructor.prototype;
        // Replace the method with a spy
        var func = sinon.spy(proto, '_btnClick');
        // Select the elemen to test
        var btn = fixture('fixture-one').shadowRoot.querySelector('.btn');
        // Simulate the trigger
        btn.click();
        // Check if the function was called
        sinon.assert.called(func);
    });
于 2017-06-25T14:42:10.320 回答