Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ How to Test Custom Hook in ReactJS

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š How to Test Custom Hook in ReactJS


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

What is a custom hook? ๐Ÿค”

Custom hooks in ReactJS are reusable pieces of code that encapsulate logic and state management. As developers, we need to ensure that these hooks work as intended and do not have any unintended side effects. This is where testing custom hooks becomes crucial.

In this article, we will explore how to test custom hooks in ReactJS using the useClipboard hook as an example.

What is the useClipboard hook? ๐Ÿค”

The useClipboard hook is a simple hook that allows you to copy text to the clipboard. It takes three parameters: the text to copy, the delay (in ms) to switch back to the initial state once copied, and a callback function to execute when the content is copied to the clipboard.

You can read more about how it uses the clipboard API to copy the text here.

import { useCallback, useEffect, useState } from 'react';

const useClipboard = (
  value: string,
  timeout = 1500,
  callBack?: () => void
) => {
  const [hasCopied, setHasCopied] = useState(false);
  const [valueState, setValueState] = useState(value);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(valueState);
      setHasCopied(true);
      callBack && callBack();
    } catch (error) {
      setHasCopied(false);
    }
  }, [valueState]);

  useEffect(() => setValueState(value), [value]);

  useEffect(() => {
    let timeoutId: number | null = null;

    if (hasCopied) {
      timeoutId = Number(
        setTimeout(() => {
          setHasCopied(false);
        }, timeout)
      );
    }

    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [timeout, hasCopied]);

  return {
    onCopyToClipBoard: handleCopy,
    hasCopied,
  };
};

Test the useClipboard hook ๐Ÿงช

We first need to create a test file to begin testing the hook. Let's call it useClipboard.test.tsx. In this file, we'll import the useClipboard hook and any necessary dependencies.

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

What is renderHook ? ๐Ÿ’ก

renderHook is a function provided by the @testing-library/react-hooks library that allows you to test React hooks in isolation.

  • It provides a testing environment for React hooks by rendering them in a mock component.

  • It allows you to test the hook's behavior and state changes in isolation, without the need for a full React component.

  • It returns an object with a result property that holds the current state of the hook.

Alright, now we know what is renderHook function and how it works.

Next, we'll write our first test to check if the hook returns an object with two properties: onCopyToClipBoard and hasCopied.

Should return an object with two properties ๐Ÿงช

it('should return an object with onCopyToClipBoard and hasCopied properties', () => {
  const { result } = renderHook(() => useClipboard('test'));
  expect(result.current).toHaveProperty('onCopyToClipBoard');
  expect(result.current).toHaveProperty('hasCopied');
});

In this test, we render the hook using the renderHook function from @testing-library/react-hooks. We pass in the text we want to copy as the first argument. Then we use the expect function to check if the hook returns an object with the two properties we expect.

Next, we'll write a test to check if the onCopyToClipBoard function updates the hasCopied state.

Should update the state ๐Ÿงช

it('should update hasCopied state when content is copied to clipboard', async () => {
  const { result } = renderHook(() => useClipboard('test'));
  await act(async () => {
    result.current.onCopyToClipBoard();
  });
  expect(result.current.hasCopied).toBe(true);
});

In this test, we call the onCopyToClipBoard function and use the await keyword to wait for the function to finish executing. We then check if the hasCopied the state is set to true.

Finally, we'll write a test to check if the hasCopied state resets after the timeout.

Should reset the state after a timeout ๐Ÿงช

it('should reset hasCopied state after timeout', async () => {
  jest.useFakeTimers();
  const { result, rerender } = renderHook(() =>
    useClipboard('test', 1500)
  );
  await act(async () => {
    result.current.onCopyToClipBoard();
  });
  expect(result.current.hasCopied).toBe(true);
  act(() => {
    jest.advanceTimersByTime(1500);
  });
  rerender();
  expect(result.current.hasCopied).toBe(false);
  jest.useRealTimers();
});

In this test, we use the jest.useFakeTimers() function to fake the timer. We render the hook with a delay of 1500ms and call the onCopyToClipBoard function. We then advance the timer by 1500ms and rerender the hook. Finally, we check if the hasCopied state is set to false.

Conclusion โœจ

Testing custom hooks in ReactJS is crucial for ensuring the functionality of our components. While it may be challenging at times, with the right approach and tools like @testing-library/react-hooks, we can write effective tests and ensure our hooks work as intended.

And thatโ€™s it for this topic. Thank you for reading.

If you found this article useful, please consider liking and sharing it with others. If you have any questions, feel free to comment, and I will do my best to respond.

Resource ๐Ÿ’ก

Connect with me ๐Ÿ‘‹

...



๐Ÿ“Œ How to Test Custom Hook in ReactJS


๐Ÿ“ˆ 45.74 Punkte

๐Ÿ“Œ Commonly asked ReactJS interview questions. Here are ReactJS interview questions and answers


๐Ÿ“ˆ 34.89 Punkte

๐Ÿ“Œ Hook error handling doesnโ€™t catch errors in ReactJS


๐Ÿ“ˆ 33.26 Punkte

๐Ÿ“Œ How to Create your Own useWindowSize Hook in ReactJS


๐Ÿ“ˆ 33.26 Punkte

๐Ÿ“Œ Difference between Action Hook and Filter Hook in WordPress


๐Ÿ“ˆ 31.63 Punkte

๐Ÿ“Œ Build a custom image uploader with ReactJS


๐Ÿ“ˆ 26.25 Punkte

๐Ÿ“Œ Writing a Custom React useDebounce Hook with Typescript


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ Writing a Custom useWindowSize React Hook


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ Using Local Storage in React with Your Own Custom useLocalStorage Hook


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ How to Build a Custom React Hook to Listen for Keyboard Events


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ A Guide to Debouncing in JavaScript and React | Create a Customย Hook


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ Pass a ref to a custom hook


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ How to Create a Custom React Hook โ€“ a Hands-on Tutorial


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ custom fetch hook


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ React Magic: How to Create a Custom Hook for Seamless Data Retrieval.


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ React Custom Hook: useDidMountEffect


๐Ÿ“ˆ 24.62 Punkte

๐Ÿ“Œ Bugtraq: Admin Custom Login WordPress plugin custom login page affected by persistent Cross-Site Scripting


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ WordPress Absolutely Glamorous Custom Admin ag-custom-admin Plugin Database Backup Arbitrary File Download Vulnerability


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ [Custom Linux ISO] An Arch Linux Based Custom Live ISO For Everyone #lovelinux


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ [Custom Linux ISO] An Arch Linux Based Custom Live ISO For Everyone #lovelinux


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ Low CVE-2019-14789: Custom 404 pro project Custom 404 pro


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ HackerOne: Custom Field Attributes may be created and updated for customers with Custom Field Trial enabled


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ Low CVE-2019-15838: Custom 404 pro project Custom 404 pro


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ DomainMod up to 4.11.01 Custom Domain admin/domain-fields/ Add Custom cross site scripting


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ Low CVE-2020-14063: Tc custom javascript project Tc custom javascript


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ Medium CVE-2015-3173: Custom content type manager project Custom content type manager


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ CVE-2022-28979 | Lifreay Portal/DXP Custom Facet Widget Custom Parameter Name cross site scripting


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ Amazon SageMaker JumpStart now offers Amazon Comprehend notebooks for custom classification and custom entity detection


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ How to use custom losses with custom gradients in TensorFlow with Keras


๐Ÿ“ˆ 17.62 Punkte

๐Ÿ“Œ 12 New CREATIVE Custom GPTS (Copy These) Custom GPT Ideas


๐Ÿ“ˆ 17.62 Punkte











matomo