How to test SetTimeout function calld in VUE Created HOOK? using Vue utils - JEST

Viewed 1328

I have an alert component which has a flag isVisible, this flag is becoming true when the component is created, and also in the created HOOK I have a setTimeout which starts if the component receives DESTROY boolean prop:

props: {
  destroy: {
    type: Boolean,
    default: false,
  },
}
data() {
  return {
    isVisible: false,
  }
}
created() {
  this.isVisible = true
  if (this.destroy) {
    setTimeout(() => {
      this.isVisible = false
    }, 2500)
  },
}

I am using VUE UTILS / JEST to test if the component disappears after setTimeout is over, I've tried:

test('Component dissapears after 2.5 seconds when it receives DESTROY prop', async () => {
  const component = wrapper.get('[data-test-id="info-alert-wrapper"]')
  await wrapper.setProps({
    destroy: true,
  })

  await wrapper.vm.$options.created.call()

  expect(component.isVisible()).toBeFalsy()
})

But it responds: TypeError: Cannot set property 'isVisible' of undefined

Can somebody help me with this? thank u! :)

2 Answers

Your need to use fake timers here. After all imports call jest.useFakeTimers(). Then in test after mounting the component call jest.runTimersToTime(2500). And after that you can do your assertions. Test example:

jest.useFakeTimers()

test('Component disappears after 2.5 seconds when it receives DESTROY prop', () => {
  const wrapper = shallowMount(YourSuperComponent, {
    propsData: {
      destroy: true
    }
  })
  jest.runTimersToTime(2500)
  expect(wrapper.vm.isVisible).toBe(false)
})

Answer from @Eduardo is correct, just noting that Jest renamed runTimersToTime() to advanceTimersByTime() since Jest 22.0.0

Related