4

I have a setup similar as the example in the docs where my composition lives in a separate file from my component as follows:

// 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>

I would like to write a separate (Jest based) test file for just the composition.js file. However, when calling the composition directly, Vue will error out (expectedly):

// composition.test.js

import useComposition from './composition';

describe('Composition', () => {
  it('Works', () => {
    useComposition();
    // Error: [vue-composition-api] "onMounted" get called outside of "setup()"
  });
});

I've tried mounting a mock composition API based component in order to provide a setup() function, but having some trouble getting it to work:

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

Does anybody have any bright ideas on how to get this to work so I can write tests for my modular compositions?

4

1 回答 1

7

The error [Vue warn]: Failed to mount component: template or render function not defined. is caused by the fact that @vue/composition-api doesn't have support for returning the render function in the setup function. With that knowledge, I was able to create a valid mock component render function. The following seems to work as expected:

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);
    });
});
于 2020-02-01T00:08:16.910 回答