如何添加< canvas>支持我在Jest中的测试? [英] How to add <canvas> support to my tests in Jest?

查看:599
本文介绍了如何添加< canvas>支持我在Jest中的测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Jest 单元测试中,我正在使用

In my Jest unit test I am rendering a component with a ColorPicker. The ColorPicker component creates a canvas object and 2d context but returns 'undefined' which throws an error "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"

我在弄清楚为什么我无法获得2D上下文时遇到了麻烦.也许我的测试配置有问题?

I'm having troubles figuring out why I can't get a 2d context. Maybe there an issue with my test config?

"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
}

推荐答案

这是因为您的测试未在真正的浏览器中运行. Jest使用jsdom来模拟DOM的必要部分,以便能够在Node中运行测试,从而避免了样式计算和呈现浏览器通常会执行的渲染.这很酷,因为这可以使测试更快.

It's because your test doesn't run in a real browser. Jest uses jsdom for mocking the necessary parts of the DOM to be able to run the tests in Node, thus avoiding style calculation and rendering that a browser would normally do. This is cool because this makes tests fast.

另一方面,如果您的组件中需要浏览器API,那么在浏览器中要困难得多.幸运的是, jsdom支持画布.您只需要配置它:

On the other hand, if you need browser APIs in your components, it's more difficult then in browser. Luckily, jsdom has support for canvas. You just have to configure it:

jsdom包括对使用 canvas 包的支持,以使用canvas API扩展任何<canvas>元素.为了使这项工作有效,您需要将canvas作为依赖项包含在您的项目中,作为jsdom的对等对象.如果jsdom可以找到canvas包,它将使用它,但是如果不存在,那么<canvas>元素的行为将类似于<div> s.

jsdom includes support for using the canvas package to extend any <canvas> elements with the canvas API. To make this work, you need to include canvas as a dependency in your project, as a peer of jsdom. If jsdom can find the canvas package, it will use it, but if it's not present, then <canvas> elements will behave like <div>s.

或者,您可以将Jest替换为基于浏览器的测试运行程序,例如 Karma .笑话是漂亮的越野车.

Alternatively, you could replace Jest with some browser-based test runner like Karma. Jest is pretty buggy anyway.

这篇关于如何添加&lt; canvas&gt;支持我在Jest中的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆