Sai_91
Sai_91

Reputation: 33

How to test internal functions using react hooks testing library?

I have a custom hook that I am trying to write tests for using the react hooks testing library package and I would like to know how I can test internal functions that are not returned in the custom hook but are used within other functions.

const customHook = () => {
  const [count, setCount] = React.useState(0);

  const doSomeThing = () => {
    ..code
  }

  const increment = () => {
    doSomeThing(); //Would like to make assertations on this
    setCount((x) => x + 1 );
  }

  return { count, increment }
}

export default customHook;

test

it('Should call increment', () => {
  const { result } = renderHook(() => useCustomHook())

  act(() => {
    result.current.increment();
  });

  expect(doSomeThing).toHaveBeenCalled(); //end result of what I would like help on
});

How can I write a test to see if doSomething has been called/used?

Upvotes: 1

Views: 4001

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

You can't. It's entirely internal to that hook, and no handle is provided to get at that function. So you can't mock it, and you can't call it directly. It's impossible to test only the doSomething function as you have it.

And more to the point, you shouldn't. You don't want to test at that level. This is a private implementation detail. You should test the public interface of your hook. That means test the arguments, the return values, and how calling functions the hook returns affect the next returned values.

Tests shouldn't care how a function does its job. Tests should only care that the function does its job correctly.

That means your test can only verify what doSomething does, and not whether it's been called. And as of right now, it doesn't do anything at all, so there's nothing to test.

Upvotes: 8

Related Questions