Closed LMarshallAfzal closed 6 months ago
You need to mock the SvelteKit environment to make it work with vitest. Check the superForm tests how to do it: https://github.com/ciscoheat/sveltekit-superforms/blob/main/src/tests/superForm.test.ts#L355
I am also having this issue, even after using the previously mentioned mocks. The code is fully functional, I just run into this issue when testing sveltekit-superforms with Vitest.
TypeError: Cannot read properties of undefined (reading '$set')
at Module.applyAction (/.../node_modules/@sveltejs/kit/src/runtime/client/client.js:1955:8)
at validationResponse (/.../node_modules/sveltekit-superforms/dist/client/superForm.js:1330:66)
import CreateApiKeyModal from '$components/modals/CreateApiKeyModal.svelte';
import { superValidate } from 'sveltekit-superforms';
import { yup } from 'sveltekit-superforms/adapters';
import type { APIKeysForm } from '$lib/types/apiKeys';
import { newAPIKeySchema } from '$schemas/apiKey';
import { toastStore } from '$stores';
import { faker } from '@faker-js/faker';
import userEvent from '@testing-library/user-event';
import { mockCreateApiKeyFormActionError } from '$lib/mocks/api-key-mocks';
describe('Create API Key Modal', () => {
let form: APIKeysForm;
it('closes the modal and pops a toast when there is an error with the form action', async () => {
const keyName = faker.word.noun();
const sixtyDays = new Date();
sixtyDays.setDate(sixtyDays.getDate() + 60);
mockCreateApiKeyFormActionError();
const toastSpy = vi.spyOn(toastStore, 'addToast');
form = await superValidate(yup(newAPIKeySchema));
render(CreateApiKeyModal, { createApiKeyModalOpen: true, form });
const modal = screen.getByTestId('create-api-key-modal');
await userEvent.type(within(modal).getByRole('textbox'), keyName);
await userEvent.click(screen.getByText('60 Days'));
await userEvent.click(within(modal).getByRole('button', { name: /create/i }));
expect(toastSpy).toHaveBeenCalledWith({
kind: 'error',
title: 'Creation Failed'
});
expect(modal).not.toBeInTheDocument();
});
});
import { vi } from 'vitest';
vi.mock('svelte', async (original) => {
const module = (await original()) as Record<string, unknown>;
return {
...module,
onDestroy: vi.fn()
};
});
vi.mock('$app/stores', async () => {
const { readable, writable } = await import('svelte/store');
const getStores = () => ({
navigating: readable(null),
page: readable({ url: new URL('http://localhost'), params: {} }),
session: writable(null),
updated: readable(false)
});
const page: typeof import('$app/stores').page = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subscribe(fn: any) {
return getStores().page.subscribe(fn);
}
};
const navigating: typeof import('$app/stores').navigating = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subscribe(fn: any) {
return getStores().navigating.subscribe(fn);
}
};
return {
getStores,
navigating,
page
};
});
TypeError: Cannot read properties of undefined (reading '$set') at Module.applyAction (/.../node_modules/@sveltejs/kit/src/runtime/client/client.js:1955:8) at validationResponse (/.../node_modules/sveltekit-superforms/dist/client/superForm.js:1330:66)
getting this too :(
Description I'm encountering a "TypeError: Cannot read properties of undefined (reading 'form')" error within the sveltekit-superforms library (superForm.js) during testing with Vitest unit tests. This error prevents form data from being processed successfully within tests.
Steps to Reproduce (in Testing)
superForm
andsuperValidate
functions.superForm.js
file (approximately line 181), where the code attempts to access theform
property of an object namedpostedForm
, which is undefined.Important Note This issue does not appear when using the forms in a regular (non-test) environment.
Expected Behavior Form data should be processed correctly by the superForm function, both during testing and in standard application usage.
Actual Behavior The TypeError is thrown during testing, interrupting form processing within the test environment. Debugging indicates that the postedForm object is undefined when the problematic line executes.
Environment Svelte version: 4.2.7 SvelteKit version: 2.0.0 sveltekit-superforms version: 2.10.5 joi validation library version: 17.12.2 Node.js version: 21.7.1 Testing framework: Vitest (I had the same issue with Jest) Other relevant dependencies and versions (if applicable)
Error
Test File
Component being tested