I'm writing a test for VueJS and I want to access the outermost layer of HTML. However, no matter what method I use, the outermost layer is always ignored. Anyway, I can access this outermost layer and do something with it (e.g. 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粉1992488082023-09-15 00:07:31
You can only get inner elements because outer elements are your wrappers.
Use the attachTo
installation option.
const wrapper = mount(component, { attachTo: document.body });
Then you can do the following, although I think this depends on the version. I recommend updating to the latest and greatest!
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...
A quick test suggests that the property may not be supported?
Documentation: https://v1.test-utils.vuejs .org/api/options.html#attachto
Note: When appending to the DOM, you should call wrapper.destroy() at the end of the test to remove the rendered element from the document and destroy the component instance.