Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] How to capture arguments passed to storybook actions? #369

Closed
sw-tracker opened this issue Oct 20, 2023 · 1 comment
Closed
Labels
question Further information is requested

Comments

@sw-tracker
Copy link

When testing which arguments were given to a storybook action, I use the code given below. However, there are many situations where I do not want to make an exact comparison. For example, list ordering and object IDs.

expect(args.onSubmit).toHaveBeenLastCalledWith(param1, param2);

How can I capture the arguments given to a storybook action into a variable? I can then compare against only parts of that variables, or as I wish.

@yannbf yannbf added the question Further information is requested label Oct 23, 2023
@yannbf
Copy link
Member

yannbf commented Oct 23, 2023

Hey @sw-tracker great question! It should work just the same way you would do in a jest test, with the concept of spies.

You can either assert things partially like so:

    await expect(args.onSubmit).toHaveBeenCalledWith(
      expect.stringMatching(/([A-Z])\w+/gi),
      expect.anything(),
    );

Or you can access the mocks via the arg like args.myHandlerName.mock.calls[0], like so:

    const [name, age] = args.onSubmit.mock.calls[0];
    await expect(name).toEqual('John');
    await expect(age).toEqual(25);

Here's the full source as an example:

import { expect } from '@storybook/jest';
import { within, userEvent, } from '@storybook/testing-library';

export const Demo = {
  render: (args) => (
    <button type="button" onClick={() => args.onSubmit('John', 25)}>
      Click
    </button>
  ),
  argTypes: {
    onSubmit: { action: true },
  },
  play: async ({ args, canvasElement }) => {
    await userEvent.click(within(canvasElement).getByRole('button'));
    await expect(args.onSubmit).toHaveBeenCalledWith(
      expect.stringMatching(/([A-Z])\w+/gi),
      expect.anything(),
    );

    // or get the args directly instead
    await userEvent.click(within(canvasElement).getByRole('button'));
    const [name, age] = args.onSubmit.mock.calls[0];
    await expect(name).toEqual('John');
    await expect(age).toEqual(25);
  }
};

I hope this helps!

@yannbf yannbf closed this as completed Oct 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants