vue-jest升级遇到的问题

156 阅读1分钟

shallowMount不渲染组件或者子组件内部的slot

影响: ★★★☆☆

解决:需要判断slot中的内容或引用方法则需要用mount

wrapperdestroy方法,采用unmount

影响: ★☆☆☆☆

解决:添加自定义插件兼容destroy写法

const plugin = wrapper => {
  return {
    destroy() {
      wrapper.unmount();
    }
  };
};
config.plugins.VueWrapper.install(plugin);

不存在createLocalVue,直接删除。

影响: ★☆☆☆☆

解决:删除所有createLocalVue

使用createRouter替代new RoutercurrentRoute为ref对象,eg: currentRoute.value.path

影响: ★★☆☆☆

解决:排查所有router的mock

export const getRouterMock = routes => {
  const router = createRouter({
    history: createWebHashHistory(),
    routes
  });

  // 兼容currentRoute为ref类型
  router.currentRoute = new Proxy(router.currentRoute, {
    get(target, key) {
      if (key !== 'value') {
        return target.value?.[key];
      }
      return target[key];
    }
  });
  return {
    options: {
      global: {
        mocks: {
          $router: router,
          $route: router.currentRoute
        }
      }
    },
    router
  };
};
const { options, router } = getRouterMock(routes);
const wrapper = shallowMount(SwebCloudgw, options);

router.push变为异步函数

影响: ★★☆☆☆

解决:排查所有router.push的调用 改为同步执行,再判断结果

最后贴上完整配置

import { createApp } from 'vue';
import { createWebHashHistory, createRouter } from 'vue-router';
import { config } from '@vue/test-utils';
import ElementPlus from 'element-plus';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import installGlobal from '@common/install-global';
import i18n from '@common/locale';
import http from '@common/utils/http';
import tipDirective from '@common/core/directive/tip';

const plugin = wrapper => {
  return {
    destroy() {
      wrapper.unmount();
    }
  };
};


const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'default',
      component: <div></div>
    }
  ]
});

const app = createApp();
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

// 自定义指令
tipDirective(app);
// 引用组件或插件
app.use(ElementPlus).use(router).use(i18n).use(installGlobal);

// 同步所有项目中使用的配置到config
config.global.components = app._context.components;
config.global.config.globalProperties = app._context.config.globalProperties;
config.global.directives = app._context.directives;
config.global.mixins = app._context.mixins;
config.global.provide = app._context.provide;
// mock实例方法
config.global.mocks = {
  $router: {
    ...router,
    push: () => {}
  }
};

// 安装自定义插件
config.plugins.VueWrapper.install(plugin);