javascript - 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?
解决方案
解决了!
将我的 .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
推荐阅读
- flutter - 在 Flutter 中使用 OrientationBuilder 打开键盘时如何避免方向更改?
- python - Python Pandas:group by 正在删除列
- javascript - 使用 jQuery 加载页面时如何仅显示一种语言
- pyqt5 - 突出显示qpushbutton pyqt中的单个字符
- android - 在 Android/iOS 应用中访问 Google Ads 信息
- javascript - 如何在不重置到原始位置的情况下将元素从一个 div 移动到另一个 div?(interact.js)
- python - 使用 Flask-HTTPAUTH 保护 Flask-Admin
- javascript - Three.js 四元数不能分配给只读属性
- python - 使用 Python 并行处理巨大 JSON 的最佳方法
- macos - 我可以更改 XPC 服务的服务质量级别吗?