1

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]
4
  • 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. Commented Mar 18, 2021 at 16:18
  • 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 Commented Mar 18, 2021 at 17:16
  • 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? Commented Mar 18, 2021 at 18:30
  • 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). Commented Mar 18, 2021 at 19:11

1 Answer 1

-1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.