Chris Eikrem
Chris Eikrem

Reputation: 566

Jest throws error about missing global function (vue.prototype)

I'm trying to set up unit testing for my Vue application.

I'm using Jest. I have mounted a component and I want to run tests on it. This component uses a global function (Vue.prototype), called aao, which fails to run in my tests.

Error message:

console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
[Vue warn]: Error in beforeMount hook: "TypeError: this.$aao is not a function"

found in

---> <MyProfile>
       <Root>

example.spec.ts:

import editUser from '@/components/forms/editUser.vue';
import TestComponent from '@/pages/user/UserMyProfile.vue';
import { shallowMount } from '@vue/test-utils';
import { expect } from 'chai';
import 'jest';

describe('AppLoadingScreen', () => {
    let component;

    beforeEach(() => {
        component = shallowMount(TestComponent);
    });

    it('should render Spinner on mount', () => {
        expect(component.find(editUser).exists()).to.be.true;
    });
});

AAO function:

export function dbRequest(
    method: 'get' | 'put' | 'post' | 'delete',
    endpoint: string,
    data: any,
    headers?: any,
    responseType?: 'blob' | 'json'
) {
    return new Promise<any>((resolve, reject) => {
        ...
    });
}
Vue.prototype.$aao = dbRequest;

How can I make sure that the test utils knows about this.$aao?

Upvotes: 2

Views: 1434

Answers (1)

Chris Eikrem
Chris Eikrem

Reputation: 566

SOLVED!

Changed my .spec.ts file to .spec.js, and changed the content to something like this:

import { mount, createLocalVue, shallowMount } from '@vue/test-utils';
import * as All from 'quasar';  
import dbRequest from 'src/boot/aao';  

const { Quasar, date } = All;

const components = Object.keys(All).reduce((object, key) => {
    const val = All[key];
        if (val && val.component && val.component.name != null) {
        object[key] = val;
    }
    return object;
}, {}); 

describe('Mount Quasar', () => {
    const localVue = createLocalVue();
    localVue.use(Quasar, { components });
    // Here's the solution, the global functions need to be used by the local vue component
    localVue.use(dbRequest);

    const wrapper = mount(UserMyProfile, {
        localVue,
    });
    const vm = wrapper.vm;
    // Tests here
}

Read more here: https://vue-test-utils.vuejs.org/guides/common-tips.html#applying-global-plugins-and-mixins

Upvotes: 1

Related Questions