使用 `vue-test-utils` 和 `jest` 使用 `Updated` 钩子进行测试

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

我有如下的 vue 组件代码

updated: function() {
   // set showPackages = true after all the child component render
   this.$nextTick(function() {
      this.show = this.element.show ? true : false
      this.done = true
   })
}

现在,我们要测试这个更新的钩子并检查是否设置了 this.show。

有谁知道如何为这个生命周期钩子编写测试用例吗?

您可以将 update 挂钩的逻辑提取到单独的方法中:

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

单元测试:

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

另请参阅: https://vue-test-utils.vuejs.org/guides/testing-async-components.html

补充建议:

您可以通过替换来进一步改进您的代码:

this.show = this.element.show ? true : false;

来自

this.show = !!this.element.show;

(另见:https://eslint.org/docs/rules/no-unneeded-ternary

更新的钩子在路由改变时触发,所以我们需要做的就是改变路由。

添加路由器进行测试

import { shallowMount, config, createLocalVue } from "@vue/test-utils";
import VueRouter from "vue-router";
const localVue = createLocalVue();
localVue.use(VueRouter);

启动它并添加到包装器

const router = new VueRouter({
  mode: "abstract"
});
const wrapper = shallowMount(YourComponent, {
  localVue,
  router
};

然后在测试时推送新路由

router.push('/route-1');

这将触发 updated 钩子

最简单的方法似乎是setProps,有parent会做

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