testing-react
testing-react copied to clipboard
Unintended side effect of loading preview.js in Jest
Describe the bug
Importing preview.js into setupTest.js will leak Storybook specific mocking into Jest.
To Reproduce
// in preview.js
window.Math.random = () => 0.5
// in setupJest.js
window.Math.random = () => 0.42 // this one will get overriden by the mock from preview.js
import { setGlobalConfig } from "@storybook/testing-react";
import * as globalStorybookConfig from "../.storybook/preview"; // path of your preview.js file
setGlobalConfig(globalStorybookConfig);
Expected behavior
The import of preview is meant at getting decorators and other exported variables, yet it will have the side effect of triggering all top-level code from this file.
First, it should be explicitely recommended to load this file on top of setupTest.js, in order to not erase any existing mocks
Also, user should know that loading preview.js will also trigger all side effects from this file.
This is mostly a documentation issue, rather than a bug.
Hey @eric-burel the intention of setGlobalConfig is really to apply all the global configurations that are applied in preview.js. You are free to not use it and pass your own custom configuration directly in composeStories like:
import * as stories from './Button.stories'
const { Primary } = composeStories(stories, { decorators: [...], globalTypes: {...}, parameters: {...})
However that is a valid concern, I'll update the docs to make it a bit more clear!