5
Describe the bug 我们在项目中使用了 vue2.5.x + vant + typescript 构建,并且使用了Jest做单元测试,在已构建好的项目框架中,对组件做单元测试,但在测试中,发现问题。下面是我的测试代码:
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import Home from '@/views/Home.vue';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('对Home组件进行单元测试', () => {
let getters!: any;
let store!: any;
beforeEach(() => {
getters = {
version: '0.1.2'
};
store = new Vuex.Store({
getters
});
});
// 挂载组件
const wrapper = shallowMount(Home, { store, localVue });
afterEach(() => {
// 销毁实例
wrapper.destroy();
});
test('验证Home是一个Vue的实例', () => {
expect(wrapper.isVueInstance()).toBeTruthy();
});
});
Home
组件关键代码如下:
<template>
....
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { Button, Icon, Popup } from 'vant';
import { Getter } from 'vuex-class';
import menuList from '@/data/menuList';
import CommonMixins from '@/utils/mixins/commonMixins';
// 声明引入的组件
@Component({
components: {
[Button.name]: Button,
[Icon.name]: Icon,
[Popup.name]: Popup
}
})
export default class Home extends CommonMixins { // 类方式声明当前组件
private menuList: any = menuList;
private activeNames: string[] = ['0'];
private popupShow: boolean = false;
private logoPath = require('../assets/images/Logo.svg') as string;
@Getter('version') private version: string;
private beforeCreate() {
// ...
}
private mounted() {
// ...
}
}
</script>
运行 npm run test:unit
,报下面的错误:
Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in
the docs:
https://jestjs.io/docs/en/configuration.html
Details:
D:\myWorks\uoko-fe-themes-mobile\node_modules\vant\es\popup\style\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import '../../vant-css/base.css';
^^^^^^
SyntaxError: Unexpected token import
应该是不能识别 import
。
Environment
- Device: windows10
- Browser: 谷歌
- Vant Version: v1.3.8
求解决方案。