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

[Question] How to fire custom events and event from child components? #233

Closed epszaw closed 3 years ago

epszaw commented 3 years ago

For example, we have two components:

<template>
  <button @click="customEvent">Click me</button>
</template>

<script>
export default {
  name: 'A',

  methods: {
    onClickButton() {
      this.$emit('custom-event')
    }
  }
}
</script>
<template>
  <div>
    <a data-testid="a-component" @custom-event="showWarning" />
    <p v-if="isWarningVisible" data-testid="warning">Warning text</p>
  </div>
</template>

<script>
import A from './A'

export default {
  name: 'B',

  components: {
    A,
  },

  data: () => ({
    isWarningVisible: false,
  }),

  methods: {
    showWarning() {
      this.isWarningVisible = true
    }
  }
}
</script>

Component A emits custom-event which should be handled in the B component.

How I should fire it correctly?

I found very similar workaround to official @vue/text-utils recommendation – to use $emit. It looks like:

await wrapper.getByTestId('a-component').__vue__.$emit('custom-event')

May be we should describe this moment in documentation, because fireEvent can confuse developers?


Also, if we try to use fireEvent with child component and not custom event we can face an error:

TypeError: MutationObserver is not a constructor

afontcu commented 3 years ago

Hi! You should definitely use fireEvent instead of stepping into Vue internals to emit a custom event – this makes your test rely on implementation details, and this is what we're trying to avoid here with Vue Testing Library. The MutationObserver error looks related to jest/jsdom version: https://github.com/testing-library/dom-testing-library/issues/477

epszaw commented 3 years ago

I see, will try it. Thank you!

jjaramillom commented 7 months ago

@afontcu, can I trigger a component's custom event using fireEvent? I have a use case in which creating the context to emit the custom event using clicks and filling forms is quite complex, so I would rather just emit this event directly, but I haven't been able to accomplish this. I tried creating a custom event with createEvent and then passing it to fireEvent pointing to the custom component via a data-testid, but this didn't work. Am I missing something? Is this even possible?

Thanks beforehand for your time and for this awesome library :)