【问题标题】:testing callback return value with react-hooks-testing-library使用 react-hooks-testing-library 测试回调返回值
【发布时间】:2021-06-16 01:55:36
【问题描述】:

在这个例子中,我们有一个名为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]

【问题讨论】:

  • result.current.log 不是模拟函数,log 是。但是log 与被测代码无关,尚不清楚为什么这会成为预期的一部分。我不清楚useLog 究竟是什么for,所以很难说一个好的测试会是什么样子。
  • useLog 只是一个示例 useHook,我试图了解如何从我正在测试的使用 useCallback 的钩子中测试返回方法。 @jonrsharpe
  • result.current.log 将包含您在 useLog 挂钩中定义的回调函数。如果你想测试那个函数,为什么不调用它并断言它已经完成了它应该做的事情呢?
  • 您总是需要从您要测试的内容开始。目前测试名为should increment counter - 什么计数器?期望与此有何关系?然后期望本身是 memoized 回调,它不是一个测试替身(不应该是,它是你正在测试的东西的一部分),被调用并返回 log (与代码无关你正在测试)。

标签: reactjs unit-testing testing jestjs react-hooks-testing-library


【解决方案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);
});

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2020-12-01
    • 2019-05-21
    • 2019-11-11
    • 1970-01-01
    • 2019-10-30
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多