【问题标题】:Why does document.activeElement not point to the focused element in JSDom when testing a Vue component with Jest?为什么用 Jest 测试 Vue 组件时 document.activeElement 不指向 JSDom 中的焦点元素?
【发布时间】:2020-11-28 19:11:28
【问题描述】:

我正在使用 vue-test-utilsjest 测试 Vue.js 2 组件。该组件自动将焦点设置到特定元素。 JSDom 应该指向 document.activeElement 变量中的这个元素,但即使我使用 wrapper.find(...).element.focus() 在测试中手动设置焦点,它也只会指向 body 元素。

it('focuses the default option automatically', async () => {
  const wrapper = await mount(component);
  console.log(document.activeElement); // -> <body></body>
  // expect(document.activeElement.value).toBe('none');
});

【问题讨论】:

    标签: javascript vue.js jestjs jsdom


    【解决方案1】:

    使用 vue-test-utils 挂载组件时,它不会自动连接到 JSDom。您需要使用mount() / shallowMount() 函数的attachTo 选项连接它。

    const wrapper = await mount(component, {
      attachTo: document.body, // ← added!
    });
    

    最终提示我的是酶库中的这个问题:https://github.com/enzymejs/enzyme/issues/2337#issuecomment-586583502

    另外,关于焦点,JSDom 的特定版本存在问题(v16 对我来说很好),在某些情况下,tabindex 属性是必需的:https://github.com/jsdom/jsdom/issues/2586

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 1970-01-01
      • 2019-01-02
      • 2020-01-01
      • 2019-04-19
      • 2019-09-18
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      相关资源
      最近更新 更多