vue+vuex+leaflet Jest单测踩坑指南

环境

  • Vue CLI 3
  • TypeScript 3.1.4
  • Leaflet 1.3.4

相关文档

vue-test-utils.vuejs.org/zh/guides/#…

踩坑

1、iview按需引入报错:Typescript Error : 'XXX' only refers to a type, but is being used as a value here

原因:iview默认的声明文件只声明了类型,不能当变量用于Vue全局组件注册语句中

Vue.component('Tabs', Tabs);
复制代码

解决:定义自己的ts声明文件:github.com/iview/iview…

import { Tabs, TabPane } from 'iview';

declare module 'iview/dist/types/tabs' {
    export const Tabs: Tabs;
    export const TabPane: TabPane;
}
复制代码

2.leaflet报错:"TypeError: Cannot read property '_layerAdd' of null"

原因:leaflet在map上添加图层时会将图层绘制在对应的renderer上,默认是svg;但jest默认在jsdom中执行测试,leaflet创建svg renderer时会判断当前环境是否支持svg:

function svgCreate(name) {
    return document.createElementNS('http://www.w3.org/2000/svg', name);
}
var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
var vml = !svg && (function () {
    try {
    	var div = document.createElement('div');
    	div.innerHTML = '';
    
    	var shape = div.firstChild;
    	shape.style.behavior = 'url(#default#VML)';
    
    	return shape && (typeof shape.adj === 'object');
    
    } catch (e) {
    	return false;
    }
}());
function svg$1(options) {
    return svg || vml ? new SVG(options) : null;
}
Map.include({
    _createRenderer: function (options) {
    	return (this.options.preferCanvas && canvas$1(options)) || svg$1(options);
    }
}
复制代码

在jsdom环境下svg为false,vml为false;且this.options.preferCanvas默认为false,所以_createRenderer返回null了
解决:设置this.options.preferCanvas为true,使用canvas来作为renderer

3.设置canvas作为renderer报错:Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)

原因:jsdom不支持canvas,需要额外引入包
解决:安装jest-canvas-mock包,在jest的配置文件中添加 setupFiles: ['jest-canvas-mock']

未完待续...

转载于:https://juejin.im/post/5bfab3c651882521c81146c0

你可能感兴趣的:(vue+vuex+leaflet Jest单测踩坑指南)