wd-David / svelte-component-test-recipes

Svelte component test recipes using Vitest & Testing Library with TypeScript
155 stars 5 forks source link

Form posting with use:enhance #30

Open bamthomas opened 1 year ago

bamthomas commented 1 year ago

First of all thank you for all the recipes it helped me a lot to test my app (I'm new to nodejs development). I'm trying to make unit tests on form posting with use:enhance. I'm having a

Error: Cannot call applyAction(...) on the server
    at file:///home/dev/src/iroco-app-client/node_modules/@sveltejs/kit/src/runtime/app/forms.js:11:9
    at fallback_callback (file:///home/dev/src/iroco-app-client/node_modules/@sveltejs/kit/src/runtime/app/forms.js:56:4)
    at HTMLFormElement.handle_submit (file:///home/dev/src/iroco-app-client/node_modules/@sveltejs/kit/src/runtime/app/forms.js:116:3)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

I haven't found tests on this on the sveltekit repo other than the e2e tests, neither in this repository.

Do you have examples or insights to make it work? To be more specific, before migrating to sveltekit, I was doing posting tests with MSW. I like to test the result of the request sending with MSW because it gives a grasp of the Web API without knowing the details of how the request is done on the client side. So I'd like to avoid mocking it.

More generally, as tests are executed by node, server classes are executed by node, could we imagine a way of testing client/server integration like it is done for python WSGI webapps, i.e. without actual HTTP requests and webserver ?

wd-David commented 1 year ago

I have limited knowledge about testing forms with use:enhance since we're not using SSR in my work project. Maybe e2e testing is a better approach.

Do you have a repro or sandbox link?

Skylli202 commented 1 year ago

Hi,

I'm really new to test in Svelte. First of all, @davipon, I can't be grateful enough about this repo. It learns me a ton of things.

As for the initial question of this issue, I am in the same issue as the author @bamthomas. I am using SvelteKit and I use use:enhance on my forms.

From the regular Svelte Actions, I isolated my form action like so :

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

export async function generate(requestEvent: RequestEvent):  {
  // ....
}

I'm not a professional when it comes to typing (yet!) but I figured out from SvelteKit Docs what is the type of the parameter for the SvelteKit Form Actions.

Then it becomes a simple Svelte Action to test from there, from my experience. I can imagine there is some complex case where it is not as easy as that.