在jest中测试react组件:引用错误:动作未定义

2g32fytz  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(113)

我有一个组件和一个测试失败。我得到错误ReferenceError:行为没有定义。有办法解决吗?我一直在努力阅读周围,并解决这个问题,但我还没有设法。

export const useCounter = (initialValue = 0) => {
  const [counter, setCounter] = useState(initialValue)

  const add = useCallback((delta = 1) => setCounter(counter => counter + delta), [setCounter])
  const substract = useCallback((delta = 1) => setCounter(counter => counter - delta), [setCounter])

  return (
    <>
      Count: {counter}
      {add, substract}
    </>
  )
}
import { renderHook } from '@testing-library/react-hooks'
import { useCounter } from '@/hooks/useCounter'

describe('Testing useCounter hook', () => {

  it('should add +1 to counter', () => {
    const { result } = renderHook(useCounter)

    act(() => result.current.add())
    expect(result.current.counter).toBe(1)
  })

  it('should subtract -1 to counter', () => {
    const { result } = renderHook(useCounter)

    act(() => result.current.subtract())
    expect(result.current.counter).toBe(-1)
  })
})
8iwquhpp

8iwquhpp1#

将以下代码插入到测试的顶部:

import { act } from '@testing-library/react';

API函数act()是react测试库的一部分。您可以从@testing-library/react导入它。
1.了解act()函数。

  1. An installation for react testing library.
    编码愉快!

相关问题