mardi 24 mars 2020

Question about testing React components using CustomHooks

I am just starting to learn React and Redux. Have a question about how to test in Jest.

I separate the component logic from the function component as CustomHooks and implement them in a separate file from the one that defines the component. And inside CustomHooks, it uses useState and useDispatch hooks.

・src/components/counter.tsx

import React from 'react';
import { useCounter } from 'modules/counter/operators';

const Counter: React.FC = () => {
  const { count, total, handleIncrementClick, handleResetClick } = useCounter();

  return (
    <div>
      <p>total:{total}</p>
      <p>current:{count}</p>
      <button onClinc={handleIncrementClick}>Increment</button>
      <button onClinc={handleResetClick}>Reset</button>
    </div>
  );
};

・src/modules/counter/operators.ts

import { useState, useCallback, MouseEvent } from 'react';
import { useDispatch } from 'react-redux';
import { counterActions } from 'modules/counter/slicer';

const useCounter = (): [
  string,
  (e: MouseEvent) => void,
  (e: MouseEvent) => void,
] => {
  const {count, setCount} = useState(0);
  const dispatch = useDispatch();

  const handleIncrementClick= useCallback(
    (e: MouseEvent) => {
      setCcount(count + 1);
      dispatch(counterActions.increment({ add: 1 }));
    },
    [count, dispatch]
  );
  const handleResetClick= useCallback(
    (e: MouseEvent) => {
      setCcount(0);
    },
    [count]
  );

  return [count, handleIncrementClick, handleResetClick];
};

When implemented in this way, which of the following is a better UnitTest?

1: Write a separate test for only the useCounter function that is implemented as CustomHooks and a test for the Counter component itself. (e.g., useCounter.test.ts / counter.test.tsx)

2: Test only the Counter components that use useCounter (do not write the UnitTest for useCounter itself)

Aucun commentaire:

Enregistrer un commentaire