aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-form/use-form-values/use-form-values.test.ts
blob: f86d9107506526eb7f0294de4ac4537715a1fa08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { describe, expect, it } from '@jest/globals';
import { act, renderHook } from '@testing-library/react';
import type { ChangeEvent } from 'react';
import { useFormValues } from './use-form-values';

/**
 * Generate a new change event.
 *
 * @param {string} name - The field name.
 * @param {unknown} value - The new value of the field.
 * @returns {ChangeEvent<HTMLInputElement>} The event.
 */
const generateChangeEvent = (name: string, value: unknown, type = 'text') => {
  const ev = new Event('change');
  Object.defineProperty(ev, 'target', {
    value: {
      checked: type === 'checkbox' || type === 'radio' ? value : undefined,
      name,
      type,
      value: type === 'checkbox' || type === 'radio' ? undefined : value,
    },
    writable: false,
  });

  return ev as unknown as ChangeEvent<HTMLInputElement>;
};

describe('useFormValues', () => {
  const initialValues = {
    foo: 'hello',
    bar: false,
  };
  const newValues = {
    foo: 'world',
    bar: true,
  };

  it('can initialize the values', () => {
    const { result } = renderHook(() => useFormValues(initialValues));

    expect(result.current.values.bar).toBe(initialValues.bar);
    expect(result.current.values.foo).toBe(initialValues.foo);
  });

  it('can update and reset the values', () => {
    const { result } = renderHook(() => useFormValues(initialValues));

    act(() => {
      result.current.update(
        generateChangeEvent('bar', newValues.bar, 'checkbox')
      );
    });

    expect(result.current.values.bar).toBe(newValues.bar);

    act(() => {
      result.current.update(generateChangeEvent('foo', newValues.foo));
    });

    expect(result.current.values.foo).toBe(newValues.foo);

    act(() => {
      result.current.reset();
    });

    expect(result.current.values.bar).toBe(initialValues.bar);
    expect(result.current.values.foo).toBe(initialValues.foo);
  });
});