我有一个简单的混合:
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。
得到了@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;
});