storybook: [Bug]: Submit in Svelte project using sveltekit-superforms is not working

Describe the bug

When I click the submit button, nothing happens if my form is using use:enhance from sveltekit-superforms.

A form without use:enhance seems to work great.

https://github.com/storybookjs/storybook/assets/9967422/beda05ef-f2a3-402c-8cd0-c71b0e684ce6

Button.svelte

<script lang="ts">
  import './button.css';
	import { defaults, superForm } from 'sveltekit-superforms';
	import { userSchema } from './schema';
	import { zod } from 'sveltekit-superforms/adapters';

  const formData = defaults({name: 'some name'}, zod(userSchema));

  const spForm = superForm(formData, {
    onSubmit: (data) => {
      console.log('Form submitted', data);
    }
  })
  const {enhance} = spForm;

  let formElement: HTMLFormElement;
</script>

<form id="form-1" use:enhance method="POST">
  <input type="text" name="name" value="Some text"/>
  <button>Submit form with use:enhance</button> <!-- Nothing seems to happen -->
</form>

<form id="form-2" method="POST" style="margin-top: 20px;" bind:this={formElement}>
  <input type="text" name="name" value="Some text"/>
  <button>Submit form, no enhance</button> <!-- can submit -->
</form>

<button type="button" on:click={() => formElement.requestSubmit()}>Submit form, no enhance also works</button>

To Reproduce

Clone the repo, npm run storybook and visit the Button.svelte story.

System

System:
    OS: macOS 14.3.1
    CPU: (10) arm64 Apple M1 Max
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.17.1 - ~/.nvm/versions/node/v18.17.1/bin/node
    npm: 10.2.5 - ~/.nvm/versions/node/v18.17.1/bin/npm <----- active
    pnpm: 8.12.0 - ~/.nvm/versions/node/v18.17.1/bin/pnpm
  Browsers:
    Chrome: 122.0.6261.69
    Safari: 17.3.1
  npmPackages:
    @storybook/addon-essentials: ^7.6.17 => 7.6.17 
    @storybook/addon-interactions: ^7.6.17 => 7.6.17 
    @storybook/addon-links: ^7.6.17 => 7.6.17 
    @storybook/blocks: ^7.6.17 => 7.6.17 
    @storybook/svelte: ^7.6.17 => 7.6.17 
    @storybook/sveltekit: ^7.6.17 => 7.6.17 
    @storybook/test: ^7.6.17 => 7.6.17 
    eslint-plugin-storybook: ^0.8.0 => 0.8.0 
    storybook: ^7.6.17 => 7.6.17 


### Additional context

My end-goal is to mock submit requests from sveltekit-superforms with the mock service worker plugin, and test my different states of form components.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 17 (6 by maintainers)

Most upvoted comments

I’m using Bun, so it took a bit of tweaking but I got this working – thank you!

For reference, I used bun patch @storybook/sveltekit, then edit the file.

And I’ve already got msw set up for other API calls, so now I’m all good to go 😃

Solution B sounds like the most feasible, since as you said, SvelteKit does a lot both before and after the callback. I’ve come quite far with this PR but it’s specific to Superforms.

There could be a solution C, since the storybook:enhance event which is triggered in the current mock enhance, could be expanded to include all necessary data in solution B. Here’s my suggestion (source):

import type { SubmitFunction } from '@sveltejs/kit';

export type EnhanceData = {
  formElement: HTMLFormElement;
  submitFunction: SubmitFunction;
  submitEvent: SubmitEvent;
};

export function enhance(formElement: HTMLFormElement, submitFunction: SubmitFunction) {
  const listener = (e: Event) => {
    const event = new CustomEvent('storybook:enhance', {
      detail: {
        formElement,
        submitFunction,
        submitEvent: e
      }
    });
    window.dispatchEvent(event);
  };
  formElement.addEventListener('submit', listener);
  return {
    destroy() {
      formElement.removeEventListener('submit', listener);
    }
  };
}

export function applyAction() {}
export function deserialize() {}

This should be more flexible, since it allows you to hook into storybook:enhance anywhere, instead of having to do it in the metadata for the stories.

I have an idea of what’s going on here.

The Problem

Under the hood sveltekit-superforms uses enhance from $app/forms, we can see that here: https://github.com/ciscoheat/sveltekit-superforms/blob/main/src/lib/client/superForm.ts#L1588

However we mock that out, which you can see if you add a function at parameters.sveltekit_experimental.forms.enhance, that function will be called.

The problem is that the real enhance function takes in a second argument submit, which is a callback it calls when a form submits. Superform expects this callback to be called, which I guess it will then pass on to the onSubmit function that the user defines, however our mock doesn’t call that callback ever.

Solution A

Our mock never calls this second submit argument and we could try to do that, however it’s not trivial to do, because SvelteKit does some heavy transformation before calling the callback, and we’d need to do the same thing, except calling fetch which it also does. Maybe we can just copy the function body to our own mock to do the same transformations and call the submit argument?

In a perfect world we would just call SvelteKit’s enhance but then somehow stop the fetch call from happening, but I’m not sure how that would be possible.

Solution B

A lighter weight solution would be to allow users to call that submit argument in their mock definitions, eg.:

// Button.stories.ts

const meta = {
  component: Button,
  ...,
  parameters: {
    sveltekit_experimental: {
        forms: {
          enhance: (formElement, submit) => {
            // do any custom stuff
            // eg. call submit(myMockData);
          }
        }
    },
},
} satisfies Meta<Button>;

This would be easier to support, we just need to make sure formElement and submit are passed to the mock which they aren’t right now. This would put the burden on the user to figure out how to “mimic” what SvelteKit does under the hood, if they wanted to replicate that (which I think they would).

Any thoughts on all of this @paoloricciuti @benmccann?