3

我有一个简单的混合:

export const mixin = superclass => class extends superclass {
  firstUpdated() {
    super.firstUpdated();
    this.dispatchEvent(new CustomEvent('my-event', {
      bubbles: true,
      composed: true,
      detail: {
        myEventTriggered: true,
      },
    }));
  }
};

我想测试是否my-event被解雇。这是我的测试:

it('dispatches the custom event', async () => {
  const tag = class extends mixin(LitElement) {};
  const el = await fixture(`<${tag}></${tag}>`);
  setTimeout(() => el.firstUpdated());
  const { detail } = await oneEvent(el, 'my-event');
  expect(detail.myEventTriggered).to.be.true;
});

这按预期工作,但我不确定这setTimeout(() => el.firstUpdated());条线。不应该firstUpdated在之后调用await fixture吗?我只是在关注open-wc 的测试指南

4

1 回答 1

2

@daKMor得到答案:

一旦你将它添加到它执行的 dom 中,测试 firstUpdated 就会有点棘手(根据你的元素正在做的工作,会有任意延迟)https://lit-element.polymer-project.org/guide/lifecycle#首次更新

你可以做的是:

it('dispatches a custom event on firstUpdated', async () => {
  const tag = class extends mixin(LitElement) {};
  const el = fixtureSync(`<${tag}></${tag}>`);
  const ev = await oneEvent(el, 'my-event');
  expect(ev).to.exist;
});

it('dispatches a custom event on connectedCallback', async () => {
  class Foo extends mixin(class {}) {};
  const el = new Foo();
  setTimeout(() => el.connectedCallback());
  const ev = await oneEvent(el, 'my-event');
  expect(ev).to.exist;
});

注意:这是未经测试的代码 - 如果它有效,请告诉我,我们可以将该信息和一些描述添加到faq中。也许你可以做一个拉请求?

对于connectedCallback,由于此回调在调用 后立即触发fixture,因此您无法再捕获它。您可以做的是定义一个新组件并在setTimeout. 一个HTMLElementorLitElement是必需的,因为oneEvent它向元素添加了一个事件监听器。

it('dispatches a custom event on connectedCallback', () => {
  const tag = defineCE(class extends mixin(LitElement) {});
  const foo = document.createElement(`${tag}`);
  setTimeout(() => foo.connectedCallback());
  const ev = await oneEvent(foo, 'connected-callback');
  expect(ev).to.exist;
});
于 2019-03-21T09:18:45.357 回答