TypeError: Cannot read property 'setTransform' of null when using Openlayers and Jest + Enzyme

TypeError: Cannot read property 'setTransform' of null when using Openlayers and Jest + Enzyme

目前正在使用 OpenLayers ExtentInteraction,当我 运行 我的测试时,我设法得到错误,因为 运行 开玩笑地测试:

TypeError: Cannot read property 'setTransform' of null

使用以下代码:

import ExtentInteraction from 'ol/interaction/Extent';

new ExtentInteraction({
  // option
});

任何建议,因为已经很晚了,我很累。提前致谢。

这里的问题是 jsdom 浏览器不支持 canvas API 所以为了解决这个问题你可以安装这个开发依赖 jest-canvas-mock 来添加 canvas api 到 jsdom window。以下是几个步骤:

安装:

yarn add -D jest-canvas-mock

// or npm

npm i -D jest-canvas-mock

将此软件包添加为 jestsetupFiles

{
  setupFiles: ['jest-canvas-mock']
}

就是这样!