svelte-component-test-recipes icon indicating copy to clipboard operation
svelte-component-test-recipes copied to clipboard

Form posting with use:enhance

Open bamthomas opened this issue 1 year ago • 2 comments

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 ?

bamthomas avatar Jan 13 '23 09:01 bamthomas

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?

wd-David avatar Jan 15 '23 03:01 wd-David

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.

Skylli202 avatar Apr 28 '23 15:04 Skylli202