我有一个类似于the example in the docs的设置,其中我的 composition 位于与我的组件不同的文件中,如下所示:
// composition.js
import { onMounted } from '@vue/composition-api';
export default function useComposition() {
onMounted(() => {
console.log('Hello, world!');
});
}
// component.vue
<template>...</template>
<script>
import { createComponent } from '@vue/composition-api';
export default createComponent({
setup() {
useComposition();
}
})
</script>
我只想为composition.js
文件编写一个单独的(基于Jest的)测试文件。但是,直接调用合成时,Vue会出错(预期):
// composition.test.js
import useComposition from './composition';
describe('Composition', () => {
it('Works', () => {
useComposition();
// Error: [vue-composition-api] "onMounted" get called outside of "setup()"
});
});
为了提供setup()
功能,我尝试安装基于模拟合成API的组件,但是在使其工作时遇到了一些麻烦:
import { mount, createLocalVue } from '@vue/test-utils';
import VueCompositionAPI, { createComponent } from '@vue/composition-api';
import useComposition from './composition';
const localVue = createLocalVue();
localVue.use(VueCompositionAPI);
describe('Composition', () => {
it('Works', () => {
const mockComponent = createComponent({
setup() {
useComposition();
return h => h('div');
}
});
mount(mockComponent, { localVue });
// [Vue warn]: Failed to mount component: template or render function not defined.
});
});
有人对如何使它起作用有什么聪明的主意,以便我可以为我的模块化作品编写测试吗?
答案 0 :(得分:2)
错误[Vue warn]: Failed to mount component: template or render function not defined.
是由于@vue/composition-api
不支持在setup函数中返回渲染函数而导致的。有了这些知识,我就能创建一个有效的模拟组件渲染函数。以下内容似乎可以正常工作:
import VueCompositionAPI from '@vue/composition-api';
import { mount, createLocalVue } from '@vue/test-utils';
const localVue = createLocalVue();
localVue.use(VueCompositionAPI);
const mountComposition = (cb: () => any) => {
return mount(
{
setup() {
return cb();
},
render(h) {
return h('div');
}
},
{ localVue }
);
};
describe('My Test', () => {
it('Works', () => {
let value;
const component = mountComposition(() => {
value = useComposition();
});
expect(value).toBe(true);
});
});