gpt4 book ai didi

reactjs - 如何测试可以将html元素的引用传递给它的 react 钩子(Hook)

转载 作者:行者123 更新时间:2023-12-04 01:04:18 25 4
gpt4 key购买 nike

我有一个自定义钩子(Hook),它可以将可选的 ref 作为对象的属性传递给它,该钩子(Hook)将其作为参数:

export const useShortcuts = ({ ref }) => {
useEffect(() => {
const trapper = new mousetrap(ref.current);

代码有效,但我现在尝试使用 react-testing-library 编写测试。和 @testing-library/react-hooks图书馆。

我正在使用 renderHook来自 @testing-library/react-hooks但我不知道如何在组件之外创建引用或模拟引用。
  it('should create shortcuts with no ref', () => {
const ref = ????? // how do I do this

const { result } = renderHook(() => useShortcuts({ ref }), {
initialProps: true
});
});

最佳答案

您可以使用 React.createRef 创建引用
const ref = React.createRef()
下面的完整工作示例

import React, { useEffect } from 'react'
import { renderHook } from '@testing-library/react-hooks'

const useShortcuts = ({ ref }) => {
useEffect(() => {
ref.current = 1
}, [])
}


it('works', () => {
const ref = React.createRef()

const { result } = renderHook(() => useShortcuts({ ref }))
expect(ref.current).toEqual(1)
})

关于reactjs - 如何测试可以将html元素的引用传递给它的 react 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57350205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com