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;

    });

});

AAO功能:


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?


凤凰求蛊
浏览 120回答 1
1回答

阿晨1998

解决了!将我的 .spec.ts 文件更改为 .spec.js,并将内容更改为如下内容:import { mount, createLocalVue, shallowMount } from '@vue/test-utils';import * as All from 'quasar';&nbsp;&nbsp;import dbRequest from 'src/boot/aao';&nbsp;&nbsp;const { Quasar, date } = All;const components = Object.keys(All).reduce((object, key) => {&nbsp; &nbsp; const val = All[key];&nbsp; &nbsp; &nbsp; &nbsp; if (val && val.component && val.component.name != null) {&nbsp; &nbsp; &nbsp; &nbsp; object[key] = val;&nbsp; &nbsp; }&nbsp; &nbsp; return object;}, {});&nbsp;describe('Mount Quasar', () => {&nbsp; &nbsp; const localVue = createLocalVue();&nbsp; &nbsp; localVue.use(Quasar, { components });&nbsp; &nbsp; // Here's the solution, the global functions need to be used by the local vue component&nbsp; &nbsp; localVue.use(dbRequest);&nbsp; &nbsp; const wrapper = mount(UserMyProfile, {&nbsp; &nbsp; &nbsp; &nbsp; localVue,&nbsp; &nbsp; });&nbsp; &nbsp; const vm = wrapper.vm;&nbsp; &nbsp; // Tests here}在此处阅读更多信息: https ://vue-test-utils.vuejs.org/guides/common-tips.html#applying-global-plugins-and-mixins
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript