Fixing storysnap test errors when including react-konva components in your storybook component library

Photo by Annie Spratt on Unsplash

After the success of the prototype to prove out reciprocal.dev we decided to spend some time on formalising any further development. One of the tasks in order to achieve this was to build a component library for all UI elements.

The UI elements are split into two categories: HTML and Konva, with the latter only working correctly as a child of a Layer component inside of a Stage component.

I started the component library work by building the HTML components first as this was easier. This was just HTML and as I’m using Storybook for the library framework I decided to use the storysnap feature to snapshot my components.

This worked well but I encountered some issues after I introduced my first Konva component into the library, as although my story in Storybook was inside of the Layer/Stage hierarchy, there were some issues with canvas.

I would get this error message:

Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)

I followed the instructions which suggested installing the canvas npm package, but I had a new error after doing that:

Error: Uncaught 'Stage has no container. A container is required.'

Unfortunately there was no hint to a package that I needed to resolve this but after a bit of searching I found that the konva-node package would allow me to render my Konva components as part of my tests by setting its isBrowser flag to false .

In order to set this flag I needed to add this block of code at the start of my Storybook stories which would check that the code is running under Jest and import the konva-node package and set the flag.

if (process.env.NODE_ENV === 'test') {
const Konva = require('konva-node');
Konva.isBrowser = false;
}

It’s worth noting that while this makes the test suite pass it’s not actually rendering anything and the snapshot will instead just render an empty div tag.

Konva 8

At the time of writing this, post Konva 8 was announced, which solves this issue as the konva and konva-node packages have been merged.

This merge still requires the canvas package to be installed to run Konva under NodeJS, but this at least removes the error message that had me stumped for a few hours before I fixed it by installing konva-node .

I’ve not had a chance to try this extensively for myself, but will update this post once I’ve upgraded with any further tips or solutions to errors I encounter.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Colin Wren

Colin Wren

459 Followers

Currently building reciprocal.dev. Interested in building shared understanding, Automated Testing, Dev practises, Metal, Chiptune. All views my own.