如何测试在 VUE Created HOOK 中调用的 SetTimeout 函数?使用 Vue 工具 - JEST

时间:2021-06-15 06:36:18

标签: vue.js jestjs vue-test-utils

我有一个警报组件,它有一个标志 isVisible,这个标志在组件创建时变为真,并且在创建的 HOOK 中我有一个 setTimeout,如果组件收到 DESTROY,它就会启动布尔属性:

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

我正在使用 VUE UTILS / JEST 来测试 setTimeout 结束后组件是否消失,我已经尝试过:

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()
})

但它响应:TypeError: Cannot set property 'isVisible' of undefined

有人可以帮我解决这个问题吗?感谢你! :)

1 个答案:

答案 0 :(得分:0)

您需要在此处使用假计时器。 毕竟导入调用 jest.useFakeTimers()。 然后在安装组件调用 jest.runTimersToTime(2500) 后进行测试。之后你可以做你的断言。测试示例:

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)
})