Repository navigation
Mocking modules with project that uses aliases and absolute imports and keep getting .mockReturnValue is not a function #33414
Replies: 2 comments
|
Hi @kathumphries! I'm Dosu and I’m helping the storybook team. The error happens because Storybook's automocking only works when the import path in both your To fix this:
If you want to keep using aliases, you need to set up subpath imports in your If subpath imports aren't possible, you can try builder aliases or a Vite plugin workaround, but these have limitations and may require refactoring your imports in stories to match the mocked path reference. Check that your import paths match exactly and avoid using aliases in both Let me know if you need help with subpath import or builder alias setup. To reply, just mention @dosu. Docs are dead. Just use Dosu. |
|
The important detail is that In your example these are two different module specifiers: // preview.js
sb.mock(import('../src/hooks/useCustomHook.ts'), { spy: true })
// story file
import { useCustomHook } from '~/hooks/useCustomHook'Even if both resolve to the same file on disk, Storybook/Vitest-style module mocking keys off the module specifier/resolution identity. If the mock is registered for the relative path but the story imports through I would make the mock and import use the same specifier first: // .storybook/preview.ts
import { sb } from 'storybook/test'
sb.mock(import('../src/hooks/useCustomHook.ts'), { spy: true })// MyComponent.stories.tsx
import { mocked } from 'storybook/test'
import { useCustomHook } from '../src/hooks/useCustomHook.ts'
const meta = {
component: MyComponent,
beforeEach() {
mocked(useCustomHook).mockReturnValue(true)
},
}If you want to keep the One quick sanity check inside console.log('is mock', 'mockReturnValue' in useCustomHook)If that prints false, the issue is definitely module identity/resolution, not the return value or the hook itself. |
Uh oh!
There was an error while loading. Please reload this page.
Summary
On a project using Storybook 10
Next 15
Typescript
React,
I am trying to mock a module and keep getting:
TypeError: (0 , storybook_test__WEBPACK_IMPORTED_MODULE_0__.mocked)(...).mockReturnValue is not a function
I have a custom hook located at ./src/hooks/useCustomHook.ts.
And refer to this in my componets using the alias: ~/hooks/useCustomHook.ts
In my preview.js I've added:
sb.mock(import('../src/hooks/useCustomHook.ts'), { spy: true });(I've tried with and without the spy)
In my story file:
I've tried importing * as hook and setting the before each to
mocked(hook.useCustomHook).mockReturnValue(true);
I am sure I am missing something, but I can't figure out what that is. Please help with any suggestions.
Additional information
No response
Create a reproduction
No response
All reactions