处理在创建时触发的元素对象

Dealing with element objects that fire on creation

所以我有一个夹具:

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

我设置了用于测试的夹具:

<script>
  suite('my-element', () => {
    setup(() => {
      page = fixture('my-element-fixture');
    });

    test('testing', () => {
      assert.isTrue(true);
    });
  });
</script>

夹具的元素中有一个 ready() 函数:

constructor() {
        super();
      }
ready() {
        super.ready();
        this.otherElement.addEventListener('function_name', function(e) {
            //stuff
          }.bind(this)
        );
      }

并且这个 ready() 函数有一个对象调用它的元素:

this.otherElement

对象在此夹具的父级中定义:

<my-element id="my-element" otherElement="[[$.otherElement]]"></my-element>

在那里创建为:

<otherElement id="otherElement></otherElement>

并从其文件中调用:

<link rel="import" href="../otherElement/otherElement.html">

我想做的是不费心测试otherElement

过去,当我从另一个元素中得到一个元素时,我会简单地创建一个对象来代替它并使用假对象并制作假函数:

setup(() => {
  page = fixture('my-element-fixture');
  anotherElement = page.$.anotherElement;
  anotherElement.functionname = function(t) {/*do nothing*/};
});

但在过去,如您所见,该元素也在我正在测试的夹具元素中,因此 page.$.anotherElement。不确定这是否真的重要。

现在的问题是我不知道我需要做什么来覆盖 otherElement 对象,这样它就不会在 ready() 函数中被调用。

我已经尝试按照上面的设置进行操作。

我试过将元素包含到实际测试文件中。

我试过让 fixture 中的元素调用自身,假元素,实际元素。

几乎所有我能想到的。

每次对象未定义时,我都会收到类似 "this.otherElement is undefined" 或 "Cannot read property of .functionname of undefined".

的错误

有什么想法吗?

您应该能够将存根元素注入到具有测试焦点的组件中。

setup(function() {
  replace('anotherElement').with('fakeAnotherElement');
});

鉴于您的模板

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

它会被放在 dom 上

<my-Element>
 <fakeAnotherElement/>
</my-Element>

在文档中阅读更多内容: https://www.polymer-project.org/3.0/docs/tools/tests#create-stub-elements

这个很难,但在所有其他方法都失败之后,唯一的解决方案是在单元测试之外随便切入代码并更改结构,这样我就绪的函数就无法处理事情了。

首先,我在 ready 函数的内容检查周围包装了一个 if 语句,以查看 otherElement 是否未定义:

constructor() {
        super();
      }
ready() {
        super.ready();
        if (this.otherElement != undefined) {
          this.otherElement.addEventListener('function_name', function(e) {
              //stuff
            }.bind(this)
          );
        }
      }

这绕过了在真正完成任何事情之前定义它的需要,并允许我像这样制作一个自定义 otherElement 对象。

page.otherElement = {};

然后根据需要将函数分配给对象:

page.otherElement = {
   functionName: function(parameters) {/*anything*/},
};

希望这对某人有所帮助,但它非常具体,所以我知道。 GL 的 Polymer 小伙伴们!