0
votes

So i have a problem using jest and vue-test-utils to test my component with activated life cycle, for example i have component with activated hook like this

activated() {
  console.log('activated')
  this.activatedData = true
}

it will not be triggered after i executed shallowMount

const wrapper = shallowMount(MyComponent, { localVue })
expect(wrapper.vm.activatedData).toBe(true) // failed because it still false

how do i test the activated life cycle then?

2

2 Answers

2
votes

You can call the activated() hook this way:

wrapper.vm.$options.activated[0].call(wrapper.vm)

Looks hacky, but I haven't found any other way.

  • wrapper.vm.$options.activated is an array, so you need to access the first element
  • then you have to use call(wrapper.vm), to set the context (this variable), so it's called on your component and it can access its methods, data, etc.

This solution is valid for @vue/test-utils 1.1.1. I wouldn't consider it particularly safe and reliable, because it does not use the public API, so at some point it may stop working. It's still better than nothing though.

0
votes

activated life cycle hook triggers only on keep-alive components. https://vuejs.org/v2/api/#activated

For non keep-alive components use mounted instead.

If keep-alive component, have in mind that is not called during server-side rendering. If not the case, provide additional info