如何使用 Enzyme 和 Jest 测试自定义钩子事件? (使用KeyPress)

时间:2021-04-13 18:38:05

标签: javascript reactjs jestjs react-hooks

如何使用 Enzyme 和 Jest 测试自定义钩子事件? (使用KeyPress)

我当前的自定义钩子:(获取键盘用户事件并更新 keyPress)

import React,{useEffect, useState} from 'react'

const useKeyPress = () => {
    const [keyPress, setKeyPress] = useState('');

    // If pressed key is our target key then set to true

  const downHandler = (event) => {
      setKeyPress(event.code);
   }

  const upHandler = () => {
      setKeyPress('');
  };

    useEffect(() => {
        window.addEventListener('keydown', downHandler);
        window.addEventListener('keyup', upHandler);
    
        return () => {
          window.removeEventListener('keydown', downHandler);
          window.removeEventListener('keyup', upHandler);
        };
    }, [])

    return ([keyPress]);
}

export default useKeyPress;

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

感谢@Tom,我通过 react 测试库找到了解决方案。

import useKeyPress from './../../src/component/useKeyPress/useKeyPress';
import { renderHook, act } from '@testing-library/react-hooks'
import {fireEvent} from '@testing-library/react'


test('Fire Enter keyboard event', () => {
    const { result } = renderHook((() => useKeyPress()))

    act(() => {
        fireEvent.keyDown(window, { key: 'Enter', code: 'Enter' });
    })
    expect(result.current.keyPress).toBe('Enter');
});