Stephen.W
Stephen.W

Reputation: 2127

How to find component by their ID?

For Example, I have a Parent component with following template:

<Parent>
  <Child id="foo" @click="doSomething"></Child>
  <Child id="bar" @click="doSomethingElse"></Child>
</Parent>

I need to find a Child component with specific ID (say the one with id foo), so that I can let it trigger an click event to the parent. At first, I tried:

describe('Parent component', () => {
  it('will do something when Child component with id "foo" triggers "click" event.', () => {
    var wrapper = shallowMount(Parent, {
      /* some other options that doesn't matter here. */
    );
    wrapper.find('#foo').vm.$emit('click');
  });
});

It goes wrong because the wrapper return by the find method doesn't have vm method when you find by a selector, and I don't know how to do next.

Any useful help will be appreciate.

P.S I don't wan't to add extra ref the those components, because this add extra code in the implementation code.

Upvotes: 0

Views: 5409

Answers (2)

lysy.vlc
lysy.vlc

Reputation: 89

You can select child using const child = document.querySelector('PARENT > #foo');

Upvotes: 0

Linus Borg
Linus Borg

Reputation: 23968

import Child from '../src/componentsChild.vue'

const children =wrapper.findAll(Child).vm.$emit('click');
const fooChild = children.wrappers.find(wrapper => wrapper.vm.$el.id === 'foo')
foo.vm.$emit('click')

You probably could also use the reference to the component instance that's saved as __vue__ on the root element, but that would be hacky:

wrapper.find('#foo').element.__vue__.$emit('click');

Upvotes: 1

Related Questions