I'm trying to use .find() then .findComponent() on the wrapper returned by .find() but I'm getting the error 'You cannot chain findComponent off a DOM element. It can only be used on Vue Components.'.
import { shallowMount, createLocalVue } from '@vue/test-utils';
import MyComponent from './MyComponent.vue';
import MyButton from './MyButton.vue';
const wrapper = shallowMount(MyComponent, { localVue });
const sectionWrapper = wrapper.find('.section');
const button = wrapper.findComponent(MyButton);
wrapper.findComponent(MyButton) should find the MyButton component.
This error is thrown:
You cannot chain findComponent off a DOM element. It can only be used on Vue Components.
I commented out these lines and it found the component just fine:
I'm not sure why this error exists, but it seems unnecessary in this case.
I can't remember exactly why but I think there is a architectural reason for why this doesn't work (difficult/impossible to implement without significant risk/breaking changes maybe? Could be wrong).
It was briefly discussed here but with no real conclusion. If you are extremely motivated, you can attempt to remove the warning and see what happens.
Most of the time, I just recommend people search for they want directly, by adding a data-testid or test-specific selector, rather than coupling your tests to a specific DOM structure.
I would encourage to make this work for VTU 2 first, before removing the warnings, they were added because the API is not backwards compatible. You cannot search for components from a dom node.
@dobromir-hristov Where is VTU 2? I don't see any reference to it anywhere in this repo?
Regardless, I'll trust that it won't work in VTU 2. Is there any way to find a component that's below a DOM node that matches a particular CSS selector? The reason I'm trying to do wrapper.find('.class').findComponent(MyComponent) is because that seems less brittle than doing something like wrapper.findAllComponents(MyComponent)[someIndex].
VTU next: https://github.com/vuejs/vue-test-utils-next
We should add a note to the README here.
The least brittle way would be to select the comoponent/DOM node directly, either via role or data-testid or something along those lines.
For reference, implementing findComponent is quite challenging in VTU 2 (as it was here). I do not see any way to find a component below a specific CSS selector, unfortunately, sorry about that. Any help with implementing this feature would be greatly appreciated!
If it's that challenging to implement I'll just close this issue. I have yet to run into a scenario where finding a component below a specific DOM node is absolutely necessary, so I'm okay for now. Thanks for the help!