我有一个使用<canvas>
进行用户交互的React组件。
我没有使用react-canvas
或react-art
或类似的东西;
相反,我只是在componentDidMount
和componentDidUpdate
中绘制画布的2D上下文。
我尽可能多地将逻辑提取到两个独立的模块:一个包含完全纯函数,并提供独立于React的核心操作,另一个提供事件处理程序和生命周期混合,以附加到React组件。 我可以轻松地测试第一个,第二个有点嘲弄。
但是,我还想非常简单地测试主画布组件,以确保它可以在没有错误的情况下呈现,并给出一些合理的道具。
这证明相当困难,因为componentDidMount
调用this.refs.canvas.getContext('2d')
,它似乎没有在节点环境中定义。
所以我想出了以下解决方案,我不太喜欢;
它涉及修补React.createElement
并创建一个假的上下文对象:
// file: test/components/MyCanvasTest.jsx
import {describe, it} from 'mocha';
import {expect} from 'chai';
import React, {Component} from 'react';
import {declareMochaMock} from '../TestUtils';
import {
renderIntoDocument,
scryRenderedDOMComponentsWithTag,
} from 'react-addons-test-utils';
import MyCanvas from '../../src/components/MyCanvas';
describe('MyCanvas', () => {
const noop = () => {};
// These things are used in my component
// but I don't want them to actually do anything,
// so I mock them as no-ops.
const propsToMockAsNoop = [
'addEventListener',
'removeEventListener',
'setInterval',
'clearInterval',
];
propsToMockAsNoop.forEach(prop => declareMochaMock(window, prop, noop));
// This thing is used in my component
// and I need it to return a dummy value.
declareMochaMock(window, 'getComputedStyle', () => ({ width: "720px" }));
// This class replaces <canvas> elements.
const canvasMockClassName = 'mocked-canvas-component';
class CanvasMock extends Component {
render() {
return <div className={canvasMockClassName} />;
}
constructor() {
super();
this.width = 720;
this.height = 480;
}
getContext() {
// Here I have to include all the methods
// that my component calls on the canvas context.
return {
arc: noop,
beginPath: noop,
canvas: this,
clearRect: noop,
fill: noop,
fillStyle: '',
fillText: noop,
lineTo: noop,
measureText: () => 100,
moveTo: noop,
stroke: noop,
strokeStyle: '',
textAlign: 'left',
textBaseline: 'baseline',
};
}
}
const originalCreateElement = React.createElement;
declareMochaMock(React, 'createElement', (...args) => {
const newArgs = args[0] === 'canvas' ?
[CanvasMock, ...args.slice(1)] :
args;
return originalCreateElement.apply(React, newArgs);
});
it("should render a <canvas>", () => {
const element = <MyCanvas />;
const component = renderIntoDocument(element);
expect(scryRenderedDOMComponentsWithTag
(component, canvasMockClassName)).to.have.length(1);
});
});
declareMochaMock
函数定义为
// file: test/TestUtils.js
export function declareMochaMock(target, propertyName, newValue) {
let oldExisted;
let oldValue;
before(`set up mock for '${propertyName}'`, () => {
oldValue = target[propertyName];
oldExisted = Object.prototype.hasOwnProperty.call(
target, propertyName);
target[propertyName] = newValue;
});
after(`tear down mock for '${propertyName}'`, () => {
if (oldExisted) {
target[propertyName] = oldValue;
} else {
delete target[propertyName];
}
});
}
我无法使用浅渲染器,因为我的组件通过ref
访问画布,浅渲染器尚不支持ref
。
有没有办法使用我当前的单元测试框架(即,不添加Jest或类似的东西)来接近此测试,同时减少测试工具需要了解的数量?
(完整的画布组件可用here。)
答案 0 :(得分:0)
你应该可以使用:
https://www.npmjs.com/package/canvas#installation以及JSDOM。 (确保遵循操作系统的安装程序)
示例测试:
import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import { jsdom } from 'jsdom';
import Chart from '../../src/index';
const createDOM = () => jsdom('<!doctype html><html><body><div></div></body></html>');
describe('<Chart />', () => {
let DOM;
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgba(255,99,132,0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
const mountComponent = props => mount(
<Chart data={data} {...props} />,
{ attachTo: DOM.body.firstChild }
);
beforeEach(() => {
DOM = createDOM();
});
it('renders', () => {
const wrapper = mountComponent();
console.log(wrapper.html());
expect(true).to.be.true;
});
});
它正在测试安装到canvas元素的Chart.js。 我正在使用摩卡和酶,但对于你正在使用的w / e测试套件应该不同。
答案 1 :(得分:0)
我遇到了使用AVA测试Lottie动画的问题。在gor181
解决方案的帮助下,这就是我如何使其工作的方法,该方法将在2020年使用最新版本的JSDOM 16.2.1
。
首先安装canvas和JSDOM
npm i canvas jsdom --save-dev
这是使用JSDOM的示例测试:
import { mount } from 'enzyme';
import { JSDOM } from 'jsdom';
const DOM = new JSDOM('<!doctype html><html><body><div></div></body></html>');
const mountComponent = props =>
mount(<AnimationComponent options={defaultOptions} />, {
attachTo: DOM.body
});
test('Animation', t => {
const wrapper = mountComponent();
console.log(wrapper.html());
t.is(wrapper.find('div').length, 2);
});
您可以console.log DOM来查看要附加到mountComponent
console.log('DOM:', DOM);
希望这会有所帮助!