Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing with `Updated` hook with `vue-test-utils` and `jest`

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?

like image 353
Jay Dadhaniya Avatar asked Jan 20 '26 03:01

Jay Dadhaniya


2 Answers

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)

like image 86
Simon Thiel Avatar answered Jan 21 '26 20:01

Simon Thiel


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()
})
like image 39
Jean Grimbert Avatar answered Jan 21 '26 22:01

Jean Grimbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!