Nicholas Ladefoged
Nicholas Ladefoged

Reputation: 255

Testing with jest on component with custom hook

i'm trying to write test code for my component that uses a custom hook to seperate logic from view

The problem is that i cannot for whatever reason seem to actually mock this custom hook in a test.

Following is a code example of what im trying to do:


// click-a-button.tsx
    
    import {useClickAButton} from "./hooks/index";
    
    export const ClickAButton = () => {
        const { handleClick, total } = useClickAButton();
        return <button onClick={handleClick}>{total}</button>;
    }

// hooks/use-click-a-button.tsx

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

export const useClickAButton = () => {
    const [total, setTotal] = useState<number>(0);
    const handleClick = useCallback(() => {
        setTotal(total => total + 1);
    }, []);
    return {
        handleClick,
        total,
    };
}

// click-a-button.test.tsx

import * as React from 'react';
import {act} from "react-dom/test-utils";
import {render} from "@testing-library/react";
import {useClickAButton} from './hooks/index'
import {ClickAButton} from "./index";

const hooks = { useClickAButton }

test('it runs with a mocked customHook',() =>  {
    const STATE_SPY = jest.spyOn(hooks, 'useClickAButton');
    const CLICK_HANDLER = jest.fn();

    STATE_SPY.mockReturnValue({
        handleClick: CLICK_HANDLER,
        total: 5,
    });

    const component  = render(<ClickAButton />);
    expect(component.container).toHaveTextContent('5');
    act(() => {
        component.container.click();
    });
    expect(CLICK_HANDLER).toHaveBeenCalled();
})

When running the test, neither of the expects is fulfilled. Context gets to be 0 instead of the mocked 5 and the CLICK_HANDLER is never called.

All in all it seems that the jest.spyon has no effect. Please help

Upvotes: 3

Views: 3211

Answers (1)

Nicholas Ladefoged
Nicholas Ladefoged

Reputation: 255

it seems i found the answer myself.

// right after imports in test file    
jest.mock('./hooks')

is all that it took!

Upvotes: 2

Related Questions