如何对全局注册的 Vue 组件进行单元测试?

时间:2021-01-25 15:41:41

标签: unit-testing vue.js vuejs2 jestjs frontend

我有一个仓库,人们通常使用 Vue.component 作为编写组件的方式,甚至不将它们导出为 ES6 模块(这是在 SFC 出现之前)。有没有办法提取那个 Vue.component 注册并对其进行单元测试,而无需首先对其进行重构?

就像这样:

Vue.component('knife', () => {...});

我发现这不是最好的解决方案,因为我们将对该 Vue 全局实例造成命名空间污染,并且在某些部分,单元测试可能因此成为一个巨大的实例,但我只是想知道是否有一种方法。

由于我们要对其中一些组件进行单元测试,因此我们可以将它们重构为 SFC,并且测试将保证它们仍然有效。

如果您只是想说:“不要这样做”,请至少说明不这样做的更多问题。 :)

1 个答案:

答案 0 :(得分:0)

由于我们使用 Jest,我们可以使用 setup file 将 Vue 定义为全局变量,并访问它的 API 以获取全局注册的组件:

安装文件:

import VueGlobalInstance from 'vue';
// Forcing Vue to be a global var to use it on the global components.
global.Vue = VueGlobalInstance;

// This is where we can reach those Vue components.
// Vue.options.components

所以在你的 component.js 文件上:

import '@/component.js';
import { mount } from '@vue/test-utils';

describe('Component', () => {
    let props = {
         ...
    };

    const build = () => {
        const wrapper = mount(Vue.options.components['component-name'], {
            propsData: props,
        });

        return {
            wrapper,
        };
    };

    it('renders the component', () => {
        const { wrapper } = build();

        expect(wrapper).toMatchSnapshot();
    });
});

这是一个前卫的案例,你根本不应该这样做 IRL,因为全局命名空间污染。

相关问题