gpt4 book ai didi

unit-testing - 在 firstUpdated 中对 LitElement 事件进行单元测试

转载 作者:行者123 更新时间:2023-12-04 15:47:01 25 4
gpt4 key购买 nike

我有一个简单的混合:

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()); 行。不应该在 await fixture 之后调用 firstUpdated 吗?我正在关注 open-wc's testing guide .

最佳答案

@daKMor得到了答案:

testing firstUpdated is a little tricky as as soon as you add it to the dom it's executed (with an arbitrary delay depending on the work your element is doing) https://lit-element.polymer-project.org/guide/lifecycle#firstupdated

what you can do is:

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;
});

Note: this is untested code - if it works pls let me know and we could add that info and a little description to the faq. Maybe you could do a Pull Request?

对于connectedCallback,由于这个回调是在调用fixture之后立即触发的,所以你不能再捕捉到它了。您可以做的是定义一个新组件并在 setTimeout 中测试其回调函数。 HTMLElementLitElement 是必需的,因为 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;
});

关于unit-testing - 在 firstUpdated 中对 LitElement 事件进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55275282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com