在 Stencil 组件的端到端测试中找到焦点元素
Find the focused element in end-to-end test for Stencil component
如何检查在 Stencil 测试中哪个元素具有焦点?我不能像往常一样使用 document.activeElement
,因为它总是 returns undefined
...
Stencil 组件默认使用 Shadow DOM,这意味着如果 Shadow DOM 中的某些元素处于焦点中,则无法通过正常 document.activeElement
属性。另一方面,Shadow DOM 宿主元素也包含 activeElement
属性(宿主元素作为不同的文档处理)。您可以在测试中使用主机的 activeElement
属性,它应该将焦点元素保存在 Shadow DOM 内。您可以在 MDN 中阅读有关 属性 的内容。
在我的一些项目中,当一个元素获得焦点时,我会向它添加一个 class ,这有助于我稍后查询它并添加焦点样式。这是另一种查找焦点元素的方法(查询 class)。
我遇到了同样的问题并同意 Gil Fink 的观点,即 Stencil Puppeteer 抽象中似乎缺少它。
我通过检查 active element of my components shadow root is the same as the id of the element I expect to have focus. I retrieved the id of the active element using Puppetteers page.$eval(...)
的 ID 解决了这个问题,例如:
const activeElementId = await page.$eval('my-component', (el) => el.shadowRoot.activeElement.id);
const elementThatShouldBeActive = await page.find('my-component >>> #some-id');
expect(activeElementId).toEqual(elementThatShouldBeActive.id);
这适用于我的上下文,希望对您也有帮助。
我最后做了:
const activeElId = await page.evaluate(() => document.activeElement!.id);
如何检查在 Stencil 测试中哪个元素具有焦点?我不能像往常一样使用 document.activeElement
,因为它总是 returns undefined
...
Stencil 组件默认使用 Shadow DOM,这意味着如果 Shadow DOM 中的某些元素处于焦点中,则无法通过正常 document.activeElement
属性。另一方面,Shadow DOM 宿主元素也包含 activeElement
属性(宿主元素作为不同的文档处理)。您可以在测试中使用主机的 activeElement
属性,它应该将焦点元素保存在 Shadow DOM 内。您可以在 MDN 中阅读有关 属性 的内容。
在我的一些项目中,当一个元素获得焦点时,我会向它添加一个 class ,这有助于我稍后查询它并添加焦点样式。这是另一种查找焦点元素的方法(查询 class)。
我遇到了同样的问题并同意 Gil Fink 的观点,即 Stencil Puppeteer 抽象中似乎缺少它。
我通过检查 active element of my components shadow root is the same as the id of the element I expect to have focus. I retrieved the id of the active element using Puppetteers page.$eval(...)
的 ID 解决了这个问题,例如:
const activeElementId = await page.$eval('my-component', (el) => el.shadowRoot.activeElement.id);
const elementThatShouldBeActive = await page.find('my-component >>> #some-id');
expect(activeElementId).toEqual(elementThatShouldBeActive.id);
这适用于我的上下文,希望对您也有帮助。
我最后做了:
const activeElId = await page.evaluate(() => document.activeElement!.id);