vue+vuex+leaflet Jest單測踩坑指南

環境

  • Vue CLI 3
  • TypeScript 3.1.4
  • Leaflet 1.3.4

相關文檔

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

踩坑

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

緣由:iview默認的聲明文件只聲明瞭類型,不能當變量用於Vue全局組件註冊語句中git

Vue.component('Tabs', Tabs);
複製代碼

解決:定義本身的ts聲明文件:github.com/iview/iview…github

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:npm

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 = '<v:shape adj="1"/>';
    
    	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來做爲renderercanvas

3.設置canvas做爲renderer報錯:Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)

緣由:jsdom不支持canvas,須要額外引入包
解決:安裝jest-canvas-mock包,在jest的配置文件中添加 setupFiles: ['jest-canvas-mock']bash

未完待續...iview

相關文章
相關標籤/搜索