Saqo Melqon
Saqo Melqon

Reputation: 143

Testing a custom react hook written in typescript

I have a custom hook useForm written in TS and it works just fine. Testing it with @testing-library/react-hooks. The tests pass. But typescript is complaining in a one specific place - see below:

Here is the custom hooks:

import { useState } from 'react';

export function useForm<T>(initialValues: T) {
  const [values, setValues] = useState(initialValues);

  return {
    values: values,
    handleChange: (e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
      setValues({
        ...values,
        [e.target.name]: e.target.value,
      });
    },
    reset: () => setValues(initialValues),
  };
}

Here is the test:

import { renderHook, act } from '@testing-library/react-hooks';

import { useForm } from './useForm';

test('should render useForm hook', () => {
  const { result } = renderHook(() =>
    useForm({
      text: 'Note One',
    }),
  );

  expect(result.current).toBeDefined();
  expect(result.current.values.text).toBe('Note One');

  act(() => {
    result.current.handleChange({
      target: { //complains here - Type '{ name: string; value: string; }' is not assignable to type 'EventTarget & (HTMLTextAreaElement | HTMLInputElement)'.
        name: 'text',
        value: 'Note Two',
      },
    });
  });

  expect(result.current.values.text).toBe('Note Two');

  act(() => {
    result.current.reset();
  });
  expect(result.current.values.text).toBe('Note One');
});

Here is a working code sandbox: https://codesandbox.io/s/flamboyant-curie-6i5moy?file=/src/useForm.test.tsx

Upvotes: 2

Views: 2950

Answers (3)

amaify
amaify

Reputation: 21

I got into this same problem this was the fix.

// Create a mock type for the changeEvent
type MockFormEvent = ChangeEvent<HTMLInputElement | HTMLTextAreaElement>

  act(() => { result.current.handleChange({
  target: { 
    name: 'text',
    value: 'Note Two',
  }
 } as MockFormEvent);
});

This fixed it for me.

Upvotes: 0

SakoBu
SakoBu

Reputation: 4011

You can simply cast it:

 act(() => {
   result.current.handleChange({
     target: {
       name: 'text',
       value: 'Note Two',
     },
   }) as React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>;
 });

Upvotes: 1

Lin Du
Lin Du

Reputation: 102587

I will create a change event by using Event() constructor. And set the event target for this event by using Object.defineProperty(event, 'target', {value: {}, writable: false}), also see this answer. Then use type casting event as unknown as React.ChangeEvent<HTMLInputElement> cast the event.

E.g.

import "@testing-library/react-hooks/lib/dom/pure";
import { renderHook, act } from "@testing-library/react-hooks";

import { useForm } from "./useForm";

test("should render useForm hook", () => {
  const { result } = renderHook(() =>
    useForm({
      text: "Note One"
    })
  );

  expect(result.current).toBeDefined();
  expect(result.current.values.text).toBe("Note One");

  const event = new Event("change");
  Object.defineProperty(event, "target", {
    value: {
      name: "text",
      value: "Note Two"
    },
    writable: false
  });

  act(() => {
    result.current.handleChange(event as unknown as React.ChangeEvent<HTMLInputElement>);
  });

  expect(result.current.values.text).toBe("Note Two");

  act(() => {
    result.current.reset();
  });
  expect(result.current.values.text).toBe("Note One");
});

Upvotes: 2

Related Questions