在我的Jest单元测试我正在渲染一个带有 ColorPicker 的组件。 ColorPicker
组件创建一个 Canvas 对象和 2d 上下文,但返回 'undefined'
并引发错误 “Cannot set property 'fillStyle' of undefined”
if (typeof document == 'undefined') return null; // Dont Render On Server
var canvas = document.createElement('canvas');
canvas.width = canvas.height = size * 2;
var ctx = canvas.getContext('2d'); // returns 'undefined'
ctx.fillStyle = c1; // "Cannot set property 'fillStyle' of undefined"
我无法弄清楚为什么我无法获得二维上下文。也许我的测试配置有问题?
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/react-tools"
],
"moduleFileExtensions": [
"jsx",
"js",
"json",
"es6"
],
"testFileExtensions": [
"jsx"
],
"collectCoverage": true
}
最佳答案
对于那些寻找使用 create-react-app 示例的人
安装
yarn add --dev jest-canvas-mock
创建一个新的 ${rootDir}/src/setupTests.js
import 'jest-canvas-mock';
关于reactjs - 如何在 Jest 中向我的测试添加 <canvas> 支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33269093/