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)
The easiest way seems to setProps, has the parent would do
it('When parent's index change, call the updateHandler', () => {
const wrapper = mount(YourComponent, { localVue });
const spy = jest.spyOn(wrapper.vm, 'handleUpdate');
wrapper.setProps({ index : 1 });
expect(spy).toHaveBeenCalled()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With