0
votes

In this example we have a simple hook called useLog that returns a method. How do I test that it gets returned with react-hooks-testing-library. I am trying to figure out how to write the expect.

The hooks useLog:

import {  useCallback } from 'react'
export const useLog = () => {
  const log = useCallback(() => console.log("hello World"), [])
  return { log }
}

test:

import { renderHook } from '@testing-library/react-hooks'
import {useLog} from "./useCounter";

const log = jest.fn()

test('should return log metod', () => {
  const { result } = renderHook(() => useLog())

  expect(result.current.log).toHaveReturnedWith(log);
})

what I get:

Matcher error: received value must be a mock function
Received has type:  function
Received has value: [Function anonymous]
1
result.current.log isn't a mock function, log is. But log is unrelated to the code under test, it's not clear why that would be any part of the expectation. It's not clear to me what useLog is actually for, so it's hard to say what a good test for it would look like. - jonrsharpe
useLog is just a example useHook, I am trying to understand how to test a return method from a hook that I am testing that uses useCallback. @jonrsharpe - someRandomDude
result.current.log will contain the callback function that you defined inside the useLog hook. If you want to test that function, why not call it and assert that it's done what it should? - juliomalves
You always need to start from what the thing you're testing is supposed to do. Currently the test is named should increment counter - what counter? How does the expectation relate to that? Then the expectation itself is that the memoized callback, which isn't a test double (and shouldn't be, it's part of the thing you're testing), gets called and returns log (which has no connection to the code you're testing). - jonrsharpe

1 Answers

0
votes

You just need spyOn function, but your 'log' callback return nothing. It is more acceptable:

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

test('should return log metod', () => {
  const { result } = renderHook(() => useLog());
  const spy = jest.spyOn(result.current, 'log');
  act(() => {
    result.current.log();
  });

  expect(spy).toHaveReturnedWith(undefined);
  expect(spy).toBeCalledTimes(1);
  expect(spy).toReturnTimes(1);
});