如何在vue-test-utils和jest中使用动态导入测试组件

时间:2018-10-05 21:04:49

标签: unit-testing vue.js jestjs importerror vue-test-utils

我正在测试一个动态导入子组件的组件。这是该部分的屏幕截图

Parent.vue内部

Inside Parent.vue

错误

enter image description here

对于正常导入,它工作正常,但对于动态异步导入,则不能。谁能帮助您配置Jest以支持异步组件导入?

1 个答案:

答案 0 :(得分:0)

如果问题仍然存在(我没有找到任何直接答案),请尝试“存根”应导入的组件。

组件

<template>
    <div>
        <dynamic-imported-component-one id="componentOne"></dynamic-imported-component-one>
        <dynamic-imported-component-two id="componentTwo"></dynamic-imported-component-two>
    </div>
</template>
<script>
    const ComponentOne = resolve => import(/* webpackChunkName: "views/view-ComponentOne-vue" */ '../Components/ComponentOne.vue');
    const ComponentTwo = resolve => import(/* webpackChunkName: "views/view-ComponentTwo-vue" */ '../Components/ComponentTwo.vue');

    export default {
        components: {
            'dynamicImportedComponentOne': ComponentOne,
            'dynamicImportedComponentTwo': ComponentTwo }
    }
</script>

测试:

describe('SomeComponent.vue', () => {

    const stubs = {
        dynamicImportedComponentOne: '<h3>Stubbed component one</h3>',
        dynamicImportedComponentTwo: '<h3>Stubbed component one</h3>'
    }

    it('test for SomeComponent', () => {
        const wrapper = shallowMount(SomeComponent, { stubs });

        expect(wrapper.find('#componentOne').exists()).toBeTruthy();
        expect(wrapper.find('#componentTwo').exists()).toBeTruthy();
    });
});

您无法测试ComponentOne / ComponentTwo的内容,但是无论如何都应该在单独的测试中完成。