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

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

问题描述

在我的 Jest 单元测试中,我正在使用 ColorPicker.ColorPicker 组件创建一个画布对象和 2d 上下文,但返回 'undefined' 会引发错误 "Cannot set property 'fillStyle' of undefined"

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 than in the browser. Luckily, jsdom has support for canvas. You just have to configure it:

jsdom 支持使用 canvas 包来扩展任何 <canvas> 元素与画布 API.为了使这项工作,您需要在项目中包含 canvas 作为依赖项,作为 jsdom 的对等点.如果 jsdom 可以找到 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.无论如何,Jest 漂亮的车.

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

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

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