Skip to content

[Bug]: clearAllMocks not working in beforeEach or afterEach #34075

@gerardparareda

Description

@gerardparareda

Describe the bug

I am calling an API in a react component and I have setup two tests for it. The API call function is mocked in preview.tsx:

sb.mock('../src/api.ts', { spy: true });

Both tests check if the API has been called once:

export const First: Story = {
  ...
  play: async () => {
    await waitFor(() => {
      expect(fetchData).toHaveBeenCalledTimes(1);
    });
  }
};

export const Second: Story = {
  ...First,
  play: async () => {
    await waitFor(() => {
      expect(fetchData).toHaveBeenCalledTimes(1);
    });
  }
};

The second story interaction test fails when running all tests because the function has been called twice, one in each story. So I decided to use the clearAllMocks function in the beforeEach or afterEach:

import { clearAllMocks, sb } from 'storybook/test';
...
const preview: Preview = {
  ...
  beforeEach: async () => {
    clearAllMocks();
  }
}

But the second test still fails.
Image

I have working workaround, which is adding the beforeEach in every test which uses this api call function:

export const Second: Story = {
  ...
  beforeEach: async () => {
    mocked(fetchData).mockClear();
  }
}

But this is obviously less then ideal because in my real scenario there's many automocked functions in use in many tests.

Reproduction link

https://github.com/gerardparareda/storybook-mockClear-error

Reproduction steps

  1. Download the repository.
  2. npm install
  3. npm run test-storybook

System

│  Storybook Environment Info:
│

│  System:
│  OS: Linux 6.8 Ubuntu 22.04.5 LTS 22.04.5 LTS (Jammy Jellyfish)
│  CPU: (16) x64 12th Gen Intel(R) Core(TM) i7-1260P
│  Shell: 5.1.16 - /bin/bash
│  Binaries:
│  Node: 22.20.0 - /home/gerard/.nvm/versions/node/v22.20.0/bin/node
│  npm: 10.9.3 - /home/gerard/.nvm/versions/node/v22.20.0/bin/npm <----- active
│  pnpm: 10.0.0 - /home/gerard/.local/share/pnpm/pnpm
│  Browsers:
│  Chrome: 145.0.7632.116
│  Firefox: 148.0
│  npmPackages:
│  @storybook/addon-vitest: ^10.2.0 => 10.2.6
│  @storybook/react-vite: ^10.2.0 => 10.2.6
│  eslint-plugin-storybook: ^10.2.0 => 10.2.6
│  msw-storybook-addon: ^2.0.6 => 2.0.6
│  storybook: ^10.2.0 => 10.2.6

Additional context

I have searched for other issues on this matter and I could not find anything related. I consider the possibility of me not correctly understanding automocking and interaction tests. Any help is appreciated.

Metadata

Metadata

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions