最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make jest globally available in storybook - Stack Overflow

programmeradmin4浏览0评论

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 pile 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.

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 pile 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.

Share Improve this question asked Oct 14, 2020 at 8:31 klugjoklugjo 20.9k10 gold badges64 silver badges81 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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.

Import jest from storybook

import {jest} from '@storybook/jest'

const mockFunction = jest.fn()
...
发布评论

评论列表(0)

  1. 暂无评论