shallowMount(HelloWorld, {
propsData: { msg }
expect(wrapper.text()).toMatch(msg)
4. 在package.json中添加启动命令,然后在控制台执行 npm run test:unit ,可以看到测试结果
"test:unit": "vue-cli-service test:unit"
Jest 踩坑
一开始的时候jes.config.js,其实没有配置这么多东西,有些配置是遇到问题后才加的,以下记录的是遇到的问题,以及解决办法
1.全局变量报错,可以配置globals(Object)属性
2.webpack没有打包进来的包,报错,比如lodash,是以cnd形式引入的,项目中直接用_., 像这种需要配置setupFiles,把lodash添加给window对象,在src下的jest-setup.js文件内加上如下代码,这个jest-setup.js就是jest测试需要的启动文件,上面有配置
import _ from 'lodash';
if (typeof window !== 'undefined') {
window._ = _;
window.VUE_APP_DATA.resource ={'app':'cfcf'}
}
3. canvas的api报错,比如CanvasRenderingContext2D,需要安装jest-canvas-mock,把他引入jest-setup.js文件中
import 'jest-canvas-mock';
4.项目中引入第三方库报错,测试时Jest报错,export default portalCommunication; ^^^^^^ SyntaxError: Unexpected token export > 1
报错原因是node_modules下的文件默认是不会被transform的(默认配置),所以es6的写法报错了。
解决办法就是在transformIgnorePatterns中把需要transform的文件排除掉,如下代码,node_modules的文件夹都不会被transform,除了element-ui/src/mixins,
transformIgnorePatterns:["/node_modules/(?!(element-ui/src/mixins)/)"],
5.webpack指定 raw-loader!导入的文件,无法找到模块
需要将路径映射添加到我的 jest 配置中,以便让我的测试识别我设置的路径映射
"moduleNameMapper": {
"!raw-loader!@/(.*)": "<rootDir>\\src/\\$1",
6. require.context is not a function 报错,需要添加新的依赖, babel-plugin-transform-require-context
.babelrc中增加
env:{
test:{
plugins:["transform-require-context"] //修复3个jest test报错
}
}
7. CDN引入的Element UI,Element组件提示没有注册,比如HelloWorld组件中使用到了 el-button组件,就会报错是否
解决办法就是在jest-setup.js中创建lcoalVue,localVue使用Element组件,这个localVue需要被引入测试文件,测试组件的时候,使用这个localVue就可以了
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld'
import {localVue} from '@/jest-setup'
describe('HelloWorld.vue', () => {
it('renders component', () => {
const wrapper = shallowMount(HelloWorld, {localVue})
expect(wrapper.findAll('.hello-world').length).toBe(1)
8.vue i18n国际化报错:Vue warn]: Error in config.errorHandler: "TypeError: _vm.$t is not a function"
解决办法就是,把某种国际化语言引入jest-setup.js,使用test-utils的mock api来mock全局对象
参考这篇文章
https://www.cnblogs.com/jiemao/p/12777826.html
在这里贴一下jest-setup.js文件
import _ from 'lodash';
if (typeof window !== 'undefined') {
window._ = _;
import 'jest-canvas-mock'; //修复2个报错
import { config,createLocalVue } from '@vue/test-utils';
import ElementUI from 'element-ui';
import language from '@/i18n/en';
import $store from '@/store';
config.mocks={ //给test-utils设置全局变量,适用于prototype定义的方法
$t:(msg) => language[msg],
$store:$store,
const testVue = createLocalVue();
testVue.use(ElementUI);
export const localVue = testVue;
如果文章对你有帮助,不妨给我个赞,谢谢~