I have vue component code like below
updated: function() {
// set showPackages = true after all the child component render
this.$nextTick(function() {
this.show = this.element.show ? true : false
this.done = true
})
}
Now, we want to the testing of this updated hook and check that this.show is set or not.
Does anyone have any idea how to write test cases for this lifecycle hook?
You would extract the logic of your update
hook to a separate method:
updated() {
// set showPackages = true after all the child component render
this.handleUpdate();
},
methods: {
handleUpdate() {
this.$nextTick(() => {
this.show = this.element.show ? true : false;
this.done = true;
});
}
}
The unit test:
import { createLocalVue, shallowMount } from '@vue/test-utils';
import YourComponent from '@/components/YourComponent';
const localVue = createLocalVue();
describe('YourComponent.vue', () => {
test('async update lifecycle hook behavior', () => {
const wrapper = shallowMount(YourComponent, {
localVue,
propsData: {
element: {
show: false
},
done: false,
show: true
}
});
expect(wrapper.exists()).toBe(true);
expect(wrapper.vm.done).toBe(false);
wrapper.vm.handleUpdate();
wrapper.vm.$nextTick(() => {
expect(wrapper.vm.done).toBe(true);
expect(wrapper.vm.show).toBe(false);
});
});
});
See also: https://vue-test-utils.vuejs.org/guides/testing-async-components.html
Additional suggestion:
You can further improve your code by replacing:
this.show = this.element.show ? true : false;
by
this.show = !!this.element.show;
(see also: https://eslint.org/docs/rules/no-unneeded-ternary)