1

在这个例子中,我们有一个简单的钩子调用useLog,它返回一个方法。如何测试它是否通过 react-hooks-testing-library 返回。我想弄清楚如何写期望。

钩子useLog:

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

测试:

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);
})

我得到了什么:

Matcher error: received value must be a mock function
Received has type:  function
Received has value: [Function anonymous]
4

1 回答 1

-1

您只需要 spyOn 函数,但您的“日志”回调什么也不返回。它更容易接受:

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);
});
于 2021-09-01T18:35:38.583 回答