# storybook-addon-module-mock

Latest version **1.6.3** (published 2026-09-08) · MIT license · 71.7K weekly downloads

## Install

```sh
npm install storybook-addon-module-mock
pnpm add storybook-addon-module-mock
yarn add storybook-addon-module-mock
bun add storybook-addon-module-mock
```

## Health

**Score 80/100 (A)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score.

## Facts

| | |
|---|---|
| Version | 1.6.3 |
| Published | 2026-09-08 |
| First published | 2023-03-14 |
| Weekly downloads | 71.7K |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=20.0.0 |
| Dependencies | 3 |
| Unpacked size | 31 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 47 |
| Author | SoraKumo <info@croud.jp> |
| Maintainers | sora_kumo |
| Keywords | storybook, react, test, jest, mock, hook, module, import, interactions |

## Links

- npm: https://www.npmjs.com/package/storybook-addon-module-mock
- Repository: https://github.com/ReactLibraries/storybook-addon-module-mock
- npm.io page: https://npm.io/package/storybook-addon-module-mock

## Dependencies (3)

- [minimatch](https://npm.io/package/minimatch.md) ^10.2.6
- [@types/node](https://npm.io/package/@types/node.md) 26.4.1
- [react-json-tree](https://npm.io/package/react-json-tree.md) ^0.20.0

## Alternatives

- [duck](https://npm.io/package/duck.md) — 4.2M weekly downloads
- [ava](https://npm.io/package/ava.md) — 560.2K weekly downloads
- [vest](https://npm.io/package/vest.md) — 50.1K weekly downloads
- [@ethereum-waffle/mock-contract](https://npm.io/package/@ethereum-waffle/mock-contract.md) — 40.0K weekly downloads
- [aws-elasticsearch-connector](https://npm.io/package/aws-elasticsearch-connector.md) — 37.4K weekly downloads

## Recent versions

- 1.6.3 (latest) — 2026-09-08
- 1.6.2 — 2026-01-27
- 1.6.1 — 2025-12-19
- 1.6.0 — 2025-11-01
- 1.4.4 — 2025-07-24
- 1.4.3 — 2025-06-17
- 1.4.0 — 2025-06-02
- 1.3.5 — 2025-04-03
- 1.3.4 — 2024-08-15
- 1.3.3 — 2024-08-14
- 1.3.2 — 2024-08-14
- 1.3.1 — 2024-08-12
- 1.3.0 — 2024-05-12
- 1.2.3 — 2024-05-04
- 1.2.2 — 2024-05-03
- … 22 more at https://npm.io/package/storybook-addon-module-mock/versions

## README

# storybook-addon-module-mock

[![](https://img.shields.io/npm/l/storybook-addon-module-mock)](https://www.npmjs.com/package/storybook-addon-module-mock)
[![](https://img.shields.io/npm/v/storybook-addon-module-mock)](https://www.npmjs.com/package/storybook-addon-module-mock)
[![](https://img.shields.io/npm/dw/storybook-addon-module-mock)](https://www.npmjs.com/package/storybook-addon-module-mock)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/ReactLibraries/storybook-addon-module-mock)

Provides module mocking functionality like `jest.mock` on Storybook@10.

Added 'storybook-addon-module-mock' to Storybook addons.  
Only works if webpack is used in the Builder.

If you use Vite for your Builder, use this package.  
https://www.npmjs.com/package/storybook-addon-vite-mock

## Screenshot

![](https://raw.githubusercontent.com/ReactLibraries/storybook-addon-module-mock/master/document/image/image01.png)  
![](https://raw.githubusercontent.com/ReactLibraries/storybook-addon-module-mock/master/document/image/image02.png)

## usage

- Sample code (examples)  
  https://github.com/ReactLibraries/storybook-addon-module-mock/tree/master/examples/storybook-module-mock

- Online Demo  
  https://reactlibraries.github.io/storybook-addon-module-mock/

## Regarding how to interrupt a mock

Interrupt webpack's `module.exports` to allow insertion of mock.  
In doing so, disable `storybook build` optimization.

## Addon options

If include is omitted, all modules are covered.

```tsx
  addons: [
    {
      name: 'storybook-addon-module-mock',
      options: {
        include: ["**/action.*"], // glob pattern
        exclude: ["**/node_modules/**"],
      }
    }
  ],
```

### Storybook@8 & Next.js

- .storybook/main.ts

```ts
import type { StorybookConfig } from '@storybook/nextjs';

const config: StorybookConfig = {
  framework: {
    name: '@storybook/nextjs',
    options: {},
  },
  stories: ['../src/**/*.stories.@(tsx)'],
  build: {
    test: {
      disabledAddons: ['@storybook/addon-docs', '@storybook/addon-essentials/docs'],
    },
  },
  addons: [
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    {
      name: '@storybook/addon-coverage',
      options: {
        istanbul: {
          exclude: ['**/components/**/index.ts'],
        },
      },
    },
    {
      name: 'storybook-addon-module-mock',
      options: {
        exclude: ['**/node_modules/@mui/**'],
      },
    },
  ],
};

export default config;
```

### Sample1

#### MockTest.tsx

```tsx
import React, { FC, useMemo, useState } from 'react';

interface Props {}

/**
 * MockTest
 *
 * @param {Props} { }
 */
export const MockTest: FC<Props> = ({}) => {
  const [, reload] = useState({});
  const value = useMemo(() => {
    return 'Before';
  }, []);
  return (
    <div>
      <button onClick={() => reload({})}>{value}</button>
    </div>
  );
};
```

#### MockTest.stories.tsx

`createMock` replaces the target module function with the return value of `jest.fn()`.  
The `mockRestore()` is automatically performed after the Story display is finished.

```tsx
import { Meta, StoryObj } from '@storybook/react';
import { expect, userEvent, waitFor, within } from '@storybook/test';
import React, { DependencyList } from 'react';
import { createMock, getMock, getOriginal } from 'storybook-addon-module-mock';
import { MockTest } from './MockTest';

const meta: Meta<typeof MockTest> = {
  tags: ['autodocs'],
  component: MockTest,
};
export default meta;

export const Primary: StoryObj<typeof MockTest> = {
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    expect(canvas.getByText('Before')).toBeInTheDocument();
  },
};

export const Mock: StoryObj<typeof MockTest> = {
  parameters: {
    moduleMock: {
      mock: () => {
        const mock = createMock(React, 'useMemo');
        mock.mockImplementation((fn: () => unknown, deps: DependencyList) => {
          // Call the original useMemo
          const value = getOriginal(mock)(fn, deps);
          // Change the return value under certain conditions
          return value === 'Before' ? 'After' : value;
        });
        return [mock];
      },
    },
  },
  play: async ({ canvasElement, parameters }) => {
    const canvas = within(canvasElement);
    expect(canvas.getByText('After')).toBeInTheDocument();
    const mock = getMock(parameters, React, 'useMemo');
    expect(mock).toBeCalled();
  },
};

export const Action: StoryObj<typeof MockTest> = {
  parameters: {
    moduleMock: {
      mock: () => {
        const useMemo = React.useMemo;
        const mock = createMock(React, 'useMemo');
        mock.mockImplementation(useMemo);
        return [mock];
      },
    },
  },
  play: async ({ canvasElement, parameters }) => {
    const canvas = within(canvasElement);
    const mock = getMock(parameters, React, 'useMemo');
    mock.mockImplementation((fn: () => unknown, deps: DependencyList) => {
      const value = getOriginal(mock)(fn, deps);
      return value === 'Before' ? 'Action' : value;
    });
    userEvent.click(await canvas.findByRole('button'));
    await waitFor(() => {
      expect(canvas.getByText('Action')).toBeInTheDocument();
    });
  },
};
```

### Sample2

#### message.ts

```tsx
export const getMessage = () => {
  return 'Before';
};
```

#### LibHook.tsx

```tsx
import React, { FC, useState } from 'react';
import { getMessage } from './message';

interface Props {}

/**
 * LibHook
 *
 * @param {Props} { }
 */
export const LibHook: FC<Props> = ({}) => {
  const [, reload] = useState({});
  const value = getMessage();
  return (
    <div>
      <button onClick={() => reload({})}>{value}</button>
    </div>
  );
};
```

#### LibHook.stories.tsx

```tsx
import { Meta, StoryObj } from '@storybook/react';
import { expect, userEvent, waitFor, within } from '@storybook/test';
import { createMock, getMock } from 'storybook-addon-module-mock';
import { LibHook } from './LibHook';
import * as message from './message';

const meta: Meta<typeof LibHook> = {
  tags: ['autodocs'],
  component: LibHook,
};
export default meta;

export const Primary: StoryObj<typeof LibHook> = {
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    expect(canvas.getByText('Before')).toBeInTheDocument();
  },
};

export const Mock: StoryObj<typeof LibHook> = {
  parameters: {
    moduleMock: {
      mock: () => {
        const mock = createMock(message, 'getMessage');
        mock.mockReturnValue('After');
        return [mock];
      },
    },
  },
  play: async ({ canvasElement, parameters }) => {
    const canvas = within(canvasElement);
    expect(canvas.getByText('After')).toBeInTheDocument();
    const mock = getMock(parameters, message, 'getMessage');
    console.log(mock);
    expect(mock).toBeCalled();
  },
};

export const Action: StoryObj<typeof LibHook> = {
  parameters: {
    moduleMock: {
      mock: () => {
        const mock = createMock(message, 'getMessage');
        return [mock];
      },
    },
  },
  play: async ({ canvasElement, parameters }) => {
    const canvas = within(canvasElement);
    const mock = getMock(parameters, message, 'getMessage');
    mock.mockReturnValue('Action');
    userEvent.click(await canvas.findByRole('button'));
    await waitFor(() => {
      expect(canvas.getByText('Action')).toBeInTheDocument();
    });
  },
};
```

### Sample3

#### MockTest.tsx

```tsx
import React, { FC, useMemo, useState } from 'react';
interface Props {}

/**
 * MockTest
 *
 * @param {Props} { }
 */
export const MockTest: FC<Props> = ({}) => {
  const [, reload] = useState({});
  const value = useMemo(() => {
    return 'Before';
  }, []);
  return (
    <div>
      <button onClick={() => reload({})}>{value}</button>
    </div>
  );
};
```

#### MockTest.stories.tsx

```tsx
import { Meta, StoryObj } from '@storybook/react';
import { expect, userEvent, waitFor, within } from '@storybook/test';
import React, { DependencyList } from 'react';
import { createMock, getMock, getOriginal } from 'storybook-addon-module-mock';
import { MockTest } from './MockTest';

const meta: Meta<typeof MockTest> = {
  tags: ['autodocs'],
  component: MockTest,
};
export default meta;

export const Primary: StoryObj<typeof MockTest> = {
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    expect(canvas.getByText('Before')).toBeInTheDocument();
  },
};

export const Mock: StoryObj<typeof MockTest> = {
  parameters: {
    moduleMock: {
      mock: () => {
        const mock = createMock(React, 'useMemo');
        mock.mockImplementation((fn: () => unknown, deps: DependencyList) => {
          // Call the original useMemo
          const value = getOriginal(mock)(fn, deps);
          // Change the return value under certain conditions
          return value === 'Before' ? 'After' : value;
        });
        return [mock];
      },
    },
  },
  play: async ({ canvasElement, parameters }) => {
    const canvas = within(canvasElement);
    expect(canvas.getByText('After')).toBeInTheDocument();
    const mock = getMock(parameters, React, 'useMemo');
    expect(mock).toBeCalled();
  },
};

export const Action: StoryObj<typeof MockTest> = {
  parameters: {
    moduleMock: {
      mock: () => {
        const useMemo = React.useMemo;
        const mock = createMock(React, 'useMemo');
        mock.mockImplementation(useMemo);
        return [mock];
      },
    },
  },
  play: async ({ canvasElement, parameters }) => {
    const canvas = within(canvasElement);
    const mock = getMock(parameters, React, 'useMemo');
    mock.mockImplementation((fn: () => unknown, deps: DependencyList) => {
      const value = getOriginal(mock)(fn, deps);
      return value === 'Before' ? 'Action' : value;
    });
    userEvent.click(await canvas.findByRole('button'));
    await waitFor(() => {
      expect(canvas.getByText('Action')).toBeInTheDocument();
    });
  },
};
```

### Sample4

#### ReRenderArgs.tsx

```tsx
import React, { FC } from 'react';
import styled from './ReRenderArgs.module.scss';

interface Props {
  value: string;
}

/**
 * ReRenderArgs
 *
 * @param {Props} { value: string }
 */
export const ReRenderArgs: FC<Props> = ({ value }) => {
  return <div className={styled.root}>{value}</div>;
};
```

#### ReRenderArgs.stories.tsx

```tsx
import { Meta, StoryObj } from '@storybook/react';
import { expect, waitFor, within } from '@storybook/test';
import { createMock, getMock, render } from 'storybook-addon-module-mock';
import * as message from './message';
import { ReRender } from './ReRender';

const meta: Meta<typeof ReRender> = {
  tags: ['autodocs'],
  component: ReRender,
};
export default meta;

export const Primary: StoryObj<typeof ReRender> = {};

export const ReRenderTest: StoryObj<typeof ReRender> = {
  parameters: {
    moduleMock: {
      mock: () => {
        const mock = createMock(message, 'getMessage');
        return [mock];
      },
    },
  },
  play: async ({ canvasElement, parameters }) => {
    const canvas = within(canvasElement);
    const mock = getMock(parameters, message, 'getMessage');
    mock.mockReturnValue('Test1');
    render(parameters);
    await waitFor(() => {
      expect(canvas.getByText('Test1')).toBeInTheDocument();
    });
    mock.mockReturnValue('Test2');
    render(parameters);
    await waitFor(() => {
      expect(canvas.getByText('Test2')).toBeInTheDocument();
    });
  },
};
```

---
_Source: https://npm.io/package/storybook-addon-module-mock · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
