首页 > 解决方案 > Jest 抛出关于缺少全局函数的错误(vue.prototype)

问题描述

我正在尝试为我的 Vue 应用程序设置单元测试。

我正在使用 Jest。我已经安装了一个组件,我想在它上面运行测试。这个组件使用了一个名为 aao 的全局函数 (Vue.prototype),它在我的测试中无法运行。

错误信息:

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>

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

AO功能:

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;

我如何确保测试工具知道 this.$aao?

标签: javascriptvue.jsjestjs

解决方案


解决了!

将我的 .spec.ts 文件更改为 .spec.js,并将内容更改为如下内容:

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
}

在此处阅读更多信息: https ://vue-test-utils.vuejs.org/guides/common-tips.html#applying-global-plugins-and-mixins


推荐阅读