testing-library / vue-testing-library

🦎 Simple and complete Vue.js testing utilities that encourage good testing practices.
http://testing-library.com/vue
MIT License
1.07k stars 111 forks source link

Test a call to a child component via a ref #255

Closed kinoli closed 2 years ago

kinoli commented 2 years ago

I have a child component that the parent is calling a method in. Just wondering if it is possible to test what is happening there.

<ChildComponent ref="myChild" />
this.$refs.myChild.someMethod()

Is there any way to trigger that via the unit test so I can ensure what it changes, does actually happen?

afontcu commented 2 years ago

Hi! Following the design guidelines of the testing library family, you would need to interact with the component the same way a user would – that is, if that method is triggered on a click, then you would click on the right element, and so on.

If you share a complete test example maybe we could find a solution!

kinoli commented 2 years ago

So in this situation you would need access to the component instance in order to test what is happening.

// PARENT COMPONENT <ChildComponent ref="myChild" />

// call method in child myChild.childMethod();

// CHILD COMPONENT

export default {
    name: 'ChildComponent',
      setup () {
          return  {
              childMethod = () => {
                  // there's no way to test this unless I can call it directly from the test suite
                  console.log('this was called from parent');
              }
          }
      }
}

So, there's nothing in my child component that calls that method. Only some action that happens in the parent that calls it via a ref. But the logic still needs to be tested in the child component.

So ideally, I could do something like this in my unit test.

const {instance} = render(ChildComponent);
instance.childMethod();
expect(somethingJustHappened).toBeInTheDocument();
afontcu commented 2 years ago

Only some action that happens in the parent that calls it via a ref

What's the action that triggers the parent call, then? You could create a simple parent wrapper and trigger the call

kinoli commented 2 years ago

There's an api response in the parent that triggers it. How would you add a wrapper to a test?

afontcu commented 2 years ago

I see – Then I guess I would test the parent component, not the child one – that is, if the child component is only triggered by parent, and parent is triggered by an API, I'd say the child component is an implementation detail that doesn't need to be tested in isolation