menu

Testing Library

Simple and complete DOM testing utilities that encourage good testing practices.

Channels
Chat
view-forward
# All channels
view-forward
# General
view-forward
# General Help
view-forward
# Angular Help
view-forward
# Cypress Help
view-forward
# DOM Help
view-forward
# React Help
view-forward
# TestCafe Help
view-forward
# Vue Help
view-forward
Team

Testing emitted events from a child component

August 8, 2019 at 3:15am

Testing emitted events from a child component

August 8, 2019 at 3:15am (Edited 8 months ago)
Hi guys, what's the best approach to test emitted events from a child component, especially when that child component requires a fairly long sequence of user inputs before it emits?
Simple example: A component that has a DatePicker for a child.
The tested (parent) component is supposed to catch the "change" event from the DatePicker and do something with it. I want to test that it catches it properly and does whatever it needs to do correctly. The DatePicker emits this "change" event when the user clicks "Apply", but first the user needs to select a date from the calendar. Maybe pick a time too, if this is a DateTimePicker.
I could do fireEvent(getByText(date.toString)) to make this work. But in vue test utils, there is wrapper.find(DatePicker).vm.$emit("change", newDate). The VTU approach seems to keep the UI of the child isolated (I don't need to know the button text is "Apply"), but it exposes the raw Vue component (instead of DOM node), which goes against the VTL principles. The trouble is, in some of our components, the number of "steps" required to fire an event is much, much higher. So, we're really tempted to stick with VTU for these cases. Ideas? Thx.

August 8, 2019 at 5:39am
Hi Matthew! As you mentioned, the main idea of VTL is to test components as DOM elements, not as component instances.
If the number of steps is the issue here, what about creating your own helper, that performs all of these steps?
// my-test.spec.js
const renderDatePicker = async () => {
const utils = render(DatePicker)
const selectDate = async (day, month) => {
// perform all steps, such as:
await fireEvent.click(utils.getByText(`month-${month}`))
await fireEvent.click(utils.getByText(`day-${day}`))
await fireEvent.click(utils.getByText('Select date'))
}
return {
...utils,
selectDate
}
}
test('selects date', async () => {
const { selectDate } = renderDatePicker()
await selectDate('25', '10')
getByText('selected date: 25th of October')
})
I made up the whole API, but you'll get the idea. Create you custom render so that it provides the right tools for the component.
Another possible solution is to drop some data-testid in the right places, so you get an easier time trying to query them (given that this is part of the problem).
Hope it helps!
Edited
  • reply
  • like
Makes sense. I’ll give that a shot. Thanks very much Adrià!
  • reply
  • like
Great, let me know how it goes!
  • reply
  • like