klugjo
klugjo

Reputation: 20885

Make jest globally available in storybook

I am using @storybook/react 6 in a create-react-app project.

I have thousands of tests and mocks for all my stores/objects and so on.

These mocks make use of jest.fn().

I would like to reuse these mocks in my storybook stories but it says jest is not defined which makes sense.

I am wondering if there is an easy way to make jest globally available when running storybook.

Currently I am adding import jest from 'jest-mock' in every mock file that I use but I am wondering if there is a better solution.

Example:

test.stories.tsx

import React from 'react';

export default {
  title: 'Test'
};

export Test = () => <button onClick={jest.fn()}>Test</button>;

Will compile but won't run -> jest is not defined error

import React from 'react';
import jest from 'jest-mock';

export default {
  title: 'Test'
};

export Test = () => <button onClick={jest.fn()}>Test</button>;

Works fine but I would like to avoid having to import jest-mock everywhere.

Upvotes: 4

Views: 8022

Answers (2)

Anderson Laverde
Anderson Laverde

Reputation: 395

Import jest from storybook

import {jest} from '@storybook/jest'

const mockFunction = jest.fn()
...

Upvotes: 0

daniloxxv
daniloxxv

Reputation: 865

You can ensure the mock will be available in all your stories by adding the following lines to the preview.js file in your project's .storybook folder:

import jest from 'jest-mock';
window.jest = jest;

From the Storybook docs:

Use preview.js for global code (such as CSS imports or JavaScript mocks) that applies to all stories.

Upvotes: 5

Related Questions