Paveloosha
Paveloosha

Reputation: 633

How to test custom hooks in React using JEST, Enzyme?

I have a Custom Hook like below

const useSum = (a = 1, b = 1) => {
  const [sum, setSum] = useState(a + b);

  useEffect(() => {
    setSum(a + b);
  }, [a, b]);

  return sum;
}

I am using this in my funcionat component

const MyFuncComp = () => {
  const sum = useSum(1, 2);
  return (
   <div>{sum}</div>
  );
}

In test case I have it like this

describe('Testing MyFuncComp', () => {
  const myFuncComp = mount(<MyFuncComp />);
  it('should have value of sum', () => {

    const expected = '3';
    const received = myFuncComp.find('div').text();
    expect(received).toEqual(expected);    
  });
})

It's never executing 'useState' or 'useEffect'. Received value is always 'undefined';

Upvotes: 16

Views: 14292

Answers (1)

lissettdm
lissettdm

Reputation: 13078

I recommend you to use: @testing-library/react-hooks

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


describe('Testing MyFuncComp', () => {
  it('should have value of sum', () => {
    const myFuncComp = renderHook(() => useSum(1,2));
    const expected = '3';
    const received = myFuncComp.result.current;
    expect(received).toEqual(expected);    
  });
})

Also I don't think you need enzyme or any lib to test your component, you can use react-dom and react-dom/test-utils

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import MyFunComp from "./MyFunComp";

let container = null;

describe("Card component", () => {
  beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement("div");
    document.body.appendChild(container);
  });

  afterEach(() => {
    // cleanup on exiting
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it("Should render correctly", async () => {
    await act(async () => {
      render(<MyFunComp />, container);
    });
    const div = container.querySelector("div");
    expect(div).toBeTruthy();
    expect(div.textContent).toBe("123");
  });
});

Upvotes: 19

Related Questions