Skip to content

Commit

Permalink
Do add spy to action for explicit actions
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperpeulen committed Feb 14, 2024
1 parent f94366e commit 152d96d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 17 deletions.
1 change: 1 addition & 0 deletions code/addons/actions/src/runtime/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export function action(name: string, options: ActionOptions = {}): HandlerFuncti
channel.emit(EVENT_ID, actionDisplayToEmit);
};
handler.isAction = true;
handler.implicit = options.implicit;

return handler;
}
52 changes: 35 additions & 17 deletions code/addons/interactions/src/preview.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,41 @@
/* eslint-disable no-underscore-dangle */
import type {
Args,
LoaderFunction,
PlayFunction,
PlayFunctionContext,
StepLabel,
} from '@storybook/types';
import type { Args, ArgsEnhancer, Renderer } from '@storybook/types';
import { instrument } from '@storybook/instrumenter';
import { fn } from '@storybook/test';

export const { step: runStep } = instrument(
{
step: (label: StepLabel, play: PlayFunction, context: PlayFunctionContext<any>) =>
play(context),
},
{ intercept: true }
);
const addSpies = (value: unknown, depth = 0): any => {
// Make sure to not get in infinite loops with self referencing args
if (depth > 5) return value;

const instrumentSpies: LoaderFunction = ({ initialArgs }) => {
if (value == null) return value;
if (
typeof value === 'function' &&
'isAction' in value &&
value.isAction &&
!('implicit' in value && value.implicit) &&
!('_isMockFunction' in value && value._isMockFunction)
) {
return fn(value as any);
}

if (Array.isArray(value)) {
return value.map((item) => addSpies(item, depth++));
}

if (typeof value === 'object') {
// We have to mutate the original object for this to survive HMR.

for (const [k, v] of Object.entries(value)) {
(value as Record<string, unknown>)[k] = addSpies(v, depth++);
}
return value;
}
return value;
};

const wrapActionsInSpyFns: ArgsEnhancer<Renderer> = ({ initialArgs }) => addSpies(initialArgs);

const instrumentSpies: ArgsEnhancer = ({ initialArgs }) => {
const argTypesWithAction = Object.entries(initialArgs).filter(
([, value]) =>
typeof value === 'function' &&
Expand All @@ -29,13 +48,12 @@ const instrumentSpies: LoaderFunction = ({ initialArgs }) => {
const instrumented = instrument({ [key]: () => value }, { retain: true })[key];
acc[key] = instrumented();
// this enhancer is being called multiple times

value._instrumented = true;
return acc;
}, {} as Args);
};

export const argsEnhancers = [instrumentSpies];
export const argsEnhancers = [wrapActionsInSpyFns, instrumentSpies];

export const parameters = {
throwPlayFunctionExceptions: false,
Expand Down

0 comments on commit 152d96d

Please sign in to comment.