我正在尝试使用呈现HTML5画布的React组件来使图像快照测试正常工作(即,模拟 not )。我正在使用Jest,React测试库,Node Canvas,Puppeteer和Jest Image Snapshot。
给出以下React组件的render()
:
public render(): React.ReactElement<TestCanvas> {
const { innerWidth, innerHeight } = window;
return (
<div id="canvas" style={{ height: `${innerHeight}px`, width: `${innerWidth}px` }}>
<canvas ref={this.canvasRef} />
</div>
);
}
这是一个Jest测试的样子:
it('should render a <TestCanvas/> component', async () => {
const { container } = render(<TestCanvas />);
const page: puppeteer.Page = await browser.newPage();
await page.setContent(container.outerHTML);
const image: string = await page.screenshot();
expect(image).toMatchImageSnapshot();
});
但是,此测试会生成空白的800x600 PNG空白图片作为基线。
但是,如果我将测试更改为此:
it('should render a <TestCanvas/> component', async () => {
const { container } = render(<TestCanvas />);
const canvas: HTMLCanvasElement = container.querySelector('canvas') as HTMLCanvasElement;
const img = document.createElement('img');
img.src = canvas.toDataURL();
const page: puppeteer.Page = await browser.newPage();
await page.setContent(img.outerHTML);
const image: string = await page.screenshot();
expect(image).toMatchImageSnapshot();
});
它可以根据我的React组件生成基准PNG快照。
我目前正在尝试调试管道中出现问题的地方。
答案 0 :(得分:1)
我已经使用不使用puppeteer的方法完成了html5 canvas图像快照,但是puppeteer方法很有趣。这是我使用的方法
test('canvas image snapshot', async () => {
const { getByTestId } = render(
<MyComponent />,
)
const canvas = await waitForElement(() =>
getByTestId('mycanvas'),
)
const img = canvas.toDataURL()
const data = img.replace(/^data:image\/\w+;base64,/, '')
const buf = Buffer.from(data, 'base64')
// may need to do fuzzy image comparison because, at least for me, on
// travis-ci it was sometimes 2 pixel diff or more for font related stuff
expect(buf).toMatchImageSnapshot({
failureThreshold: 0.5,
failureThresholdType: 'percent',
})
})
答案 1 :(得分:0)
上面@Colin的答案是需要做的。即,从画布URL删除图像编码,因为[显然]它是针对浏览器的。这是我们所做的:
it('should scroll down', () => {
const { getByTestId } = render(<PaneDrawerTestWrapper />);
const mouseHandler = getByTestId(mouseHandlerId);
act(() => {
fireEvent.wheel(mouseHandler, { deltaY: 100 });
});
const canvas = getByTestId(canvasId) as HTMLCanvasElement;
const image = stripEncoding(canvas.toDataURL());
expect(image).toMatchImageSnapshot();
});
stripEncoding
如下所示:
export function stripEncoding(canvasImageUrl: string): string {
return canvasImageUrl.replace(/^data:image\/(png|jpg);base64,/, '');
}