我有一个组件和一个测试失败。我得到错误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)
})
})
1条答案
按热度按时间8iwquhpp1#
将以下代码插入到测试的顶部:
API函数act()是react测试库的一部分。您可以从@testing-library/react导入它。
1.了解act()函数。
编码愉快!