Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using react-testing-library with storyshots?

Is it possible to use react-testing-library with the storybook storyshots addon? I'd like to generate some tests for react components which do not use enzyme.

like image 411
Mike Post Avatar asked Aug 26 '18 18:08

Mike Post


1 Answers

Probably a bit late for you, but just been looking at this exact problem. This is the config I came up with which seems to work for me.

import initStoryshots from "@storybook/addon-storyshots";
import path from "path";
import { render } from "react-testing-library";


const reactTestingLibrarySerializer = {
  print: (val, serialize, indent) => serialize(val.container.firstChild),
  test: (val) => val && val.hasOwnProperty("container")
};

initStoryshots({
  configPath: path.join(__dirname, "..", "config", "storybook"),
  framework: "react",
  integrityOptions: { cwd: path.join(__dirname, "stories") },
  renderer: render,
  snapshotSerializers: [reactTestingLibrarySerializer],
  storyKindRegex: /^((?!.*?DontTest).)*$/
});

The secret is to pass in a custom Jest serializer for the snapshotSerializers option that gets the container from the result of the render function and passes its firstChild to be serialized.

If you need to, you can modify the content of the container before serializing, to remove unstable attributes or entire elements using the DOM api.

like image 157
Matt Avatar answered Sep 23 '22 16:09

Matt