我有一个简单的混合:
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's testing guide。
答案 0 :(得分:0)
从@daKMor得到了答案:
将firstUpdated添加到执行它的dom中后,对其进行测试会有些棘手(根据您元素的工作而任意延迟)https://lit-element.polymer-project.org/guide/lifecycle#firstupdated
您可以做的是:
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
中测试其回调函数。因为HTMLElement
向元素添加了事件监听器,所以需要LitElement
或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;
});