【问题标题】:Jest throws error about missing global function (vue.prototype)Jest 抛出关于缺少全局函数的错误(vue.prototype)
【发布时间】:2020-12-03 02:20:52
【问题描述】:

我正在尝试为我的 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>

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 函数:

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?

【问题讨论】:

    标签: javascript vue.js jestjs


    【解决方案1】:

    解决了!

    将我的 .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

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2020-08-09
      • 2020-07-31
      • 2023-03-20
      • 2020-10-22
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      相关资源
      最近更新 更多