Search code examples
vue.jsvuejs2vue-componentvue-test-utils

How to acess 'emitted' of component which has been accessed through ref?


iam using

vue2-daterange-picker

which has an custom event named "update" which i want to test.

<date-range-picker
  @update="updateValues"
  ref="datePicker"
  .
  .
 >     
 </date-range-picker>

How i test the update custom event is in the coming code. Iam accessing the DateRangePicker via a ref in my test file.

it('Test update custom event', () => {
  let datePicker = cmp.vm.$refs.datePicker;
  let startDate = new Date(2019, 5, 12);
  let endDate = new Date(2019, 7, 12);
  let dpValue = { startDate, endDate };
  datePicker.$emit('update', dpValue);
  expect(datePicker._self.__emitted).toHaveProperty('update');
  expect(datePicker._self.__emitted.update[0][0]).toEqual(dpValue);
 });

The way how i access the emit property is very ugly. It works but its ugly. How can i access emitted when iam accessing the component via ref, that it looks like in the vue-test-utils example. Something like that:

const wrapper = mount(Component)
wrapper.vm.$emit('foo')
wrapper.vm.$emit('foo', 123)
expect(wrapper.emitted().foo).toBeTruthy()

So that i can get something like that in this much prettier way. I tried like example this here but it doesnt work.

datePicker.$el.emitted().update

Please help.


Solution

  • I figured it out.

       datePicker = cmp.find({ ref: 'datePicker' });
       datePicker.vm.$emit('update', new Date());
       expect(datePicker.emitted().update).toBeTruthy();