Skip to content

Commit

Permalink
Add tests for getSubmittedFormData()
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierstoval committed May 24, 2024
1 parent 7d1750f commit cf2cac8
Show file tree
Hide file tree
Showing 4 changed files with 289 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.39.0",
"intl-messageformat": "^10.5.14",
"jsdom": "^24.0.0",
"prettier": "^3.2.5",
"prettier-plugin-svelte": "^3.2.3",
"publint": "^0.2.8",
Expand Down
65 changes: 65 additions & 0 deletions src/lib/Crud/Form.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {describe, expect, it, vi} from 'vitest';
import {testOptions} from '$lib/TestOptions';
import {getSubmittedFormData} from "$lib";

describe('Submitted form data', () => {
it(
'does not work if no target is specified',
() => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);

const submitted = getSubmittedFormData({} as unknown as SubmitEvent);

expect(submitted).toStrictEqual({});
expect(consoleError).toHaveBeenCalledOnce();
expect(consoleError).toHaveBeenLastCalledWith('No form target specified. Did you forget to inject the proper SubmitEvent to the function?');
},
testOptions
);

it(
'can handle empty input',
() => {
const submitted = getSubmittedFormData(mockSubmitEvent());

expect(submitted).toStrictEqual({});
},
testOptions
);

it(
'can handle simple input',
() => {
const submitted = getSubmittedFormData(mockSubmitEvent([
['title', 'Some title'],
['description', 'Some description'],
]));

expect(submitted).toStrictEqual({
'title': 'Some title',
'description': 'Some description',
});
},
testOptions
);
});

function mockSubmitEvent(submittedData: Array<[string, string]> = []) {
const form = document.createElement('form');

const submitter = document.createElement('button');
submitter.type = 'submit';
form.appendChild(submitter);

submittedData.forEach(([key, value]) => {
const input = document.createElement('input');
input.name = key;
input.value = value;
form.appendChild(input);
});

return {
submitter: submitter,
target: form,
} as unknown as SubmitEvent;
}
1 change: 1 addition & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default defineConfig({
test: {
include: ['src/**/*.{test,spec}.ts'],
exclude: [...configDefaults.exclude, '**/build/**', '**/.svelte-kit/**', '**/dist/**'],
environment: 'jsdom',
coverage: {
exclude: [
...(configDefaults?.coverage?.exclude ?? []),
Expand Down
Loading

0 comments on commit cf2cac8

Please sign in to comment.