-->

Data binding in Polmyer's

2019-07-12 02:42发布

问题:

I am trying to test a custom Polymer element using their web-component-tester. Many of the examples make use of test-fixture. I would like to test my custom element using databinding, but I'm struggling to get data binding to work.

Essentially, I want to take my custom element, assume that the variables are bound, and assert things about it. I'm trying to follow the example in the test-fixture README. Note also that I originally posted this question on their issue tracker before realizing that Stack Overflow is probably a better place for it.

I'm defining a custom element in a my-element.html file, like follows:

<dom-module id="my-element">
  <template>
    <style>
      :host {
        display: block;
        box-sizing: border-box;
      }
    </style>
      <div id="txt-url" class="card-content">{{captureUrl}}</div>
  </template>
  <script>
    Polymer({
      is: 'my-element',
      properties: { captureUrl: String }
    });
  </script>

Here is the relevant portion of my my-element-test.html file:

<test-fixture id="my-fixture">
  <template>
    <my-element>
      <h2>seed-element</h2>
    </my-element>
  </template>
</test-fixture>

<script>
  suite('<my-element>', function() {

    var myEl;

    setup(function() {
      myEl = fixture('my-fixture', {captureUrl: 'the url'});
    });

    test('heading is captureUrl', function() {
      var urlDiv = myEl.$$('#txt-url');
      // this will obviously fail, but used for logging purposes
      assert.equal(urlDiv, boundData.captureUrl);
    });
});
</script>

When I run this I see urlDiv in the error message (console.log wasn't working for me), and the div is empty, without captureUrl bound and inserted into the function. What am I doing wrong here? Am I mis-using Polymer? Mis-using test-fixture?

回答1:

I think you're missing the binding declaration in your template:

<test-fixture id="cached-page-summary-fixture">
  <template is="dom-template">
    <cached-page-summary capture-url="{{captureUrl}}">
      <h2>seed-element</h2>
    </cached-page-summary>
  </template>
</test-fixture>

Also, you're testing <my-element> but it's not present in the test fixture template. What do you want to data bind?

EDIT

Here's the most important change I made to your code:

  1. The template inside test fixture must be <template is="dom-template">
  2. fixture() call was executed with wrong element id

Here's a gist, which works. Do bower install and then simply open test.html in your browser.