首頁  >  問答  >  主體

取得VUEjs最外層的包裝器test-utils

我正在為VueJS編寫一個測試,我想訪問HTML的最外層。然而,無論我使用什麼方法,最外層總是被忽略。無論如何,我可以訪問這個最外層,然後用它做一些事情(例如,outermostLayer.removeAttribute('key')

const originalHTML = '<main key="outermost-layer"><main>content</main></main>';     
const component = {
    template: originalHTML
};
const wrapper = mount(component);
await flushPromises();
console.log(wrapper.element.querySelector('main')); // only return the inner main       
console.log(wrapper.element.getElementsByTagName('main')); //only the inner one

P粉809110129P粉809110129401 天前522

全部回覆(1)我來回復

  • P粉199248808

    P粉1992488082023-09-15 00:07:31

    您只能取得內部元素,因為外部元素是您的包裝器。 使用 attachTo 安裝選項。

    const wrapper = mount(component, {
        attachTo: document.body
      });

    然後您可以執行以下操作,儘管我認為這取決於版本。我建議更新到最新最好的!

    console.log(wrapper.findAll('main').length); // 2 - This confirms there are 2x main elements.
      console.log(wrapper.findAll('main')[0]); // 0 - The first element.
      console.log(wrapper.findAll('main')[0].attributes('key')); // undefined - This doesn't appear to work...

    快速測試顯示可能不支援屬性?

    文件:https://v1.test-utils.vuejs .org/api/options.html#attachto

    #注意:當附加到 DOM 時,您應該在測試結束時呼叫wrapper.destroy(),以從文件中刪除渲染的元素並銷毀元件實例。

    回覆
    0
  • 取消回覆