如何使用addEventListener测试keyup

时间:2018-10-03 07:18:35

标签: jestjs enzyme

我想测试handleKeyPress方法,但是当我模拟键入时,则出现此错误:Expected spy to have been called, but it was not called.

//App.js

    componentDidMount() {
        document.addEventListener('keyup', this.handleKeyPress)
    }
    
    handleKeyPress = (event) => {
        if (event.keyCode === 38) {
            this.setState({
                up: true
            })
        }
    }
    
    
//App.test.js
    
    it('check handleKeyPress with keyup', ()=>{
        let instance = wrapper.instance()
        let handleKeyPress = spyOn(instance, 'handleKeyPress')
        wrapper.simulate('keyup', {keyCode: 38})
        expect(handleKeyPress).toHaveBeenCalled()
    })

1 个答案:

答案 0 :(得分:2)

您正在模拟组件包装器上的keyup事件,但会将keyup事件侦听器添加到文档对象。 Common Gothcas部分提到了一些有关事件传播无法正常工作的内容。

我认为实现此工作的唯一方法是监视document.addEventListener并手动调用测试文件中的处理程序。

it('check handleKeyPress with keyup', () => {

    // save keyup event handler added to document
    let keyUpHandler;
    document.addEventListener = jest.fn((event, handler) => {
        if (event === 'keyup') {
          keyUpHandler = handler;
        }
    });

    // render component
    wrapper = shallow(...); 
    let instance = wrapper.instance()
    let handleKeyPress = jest.spyOn(instance, 'handleKeyPress')

    // call the keyup handler with the event data
    keyUpHandler({ keyCode: 38 })
    expect(handleKeyPress).toHaveBeenCalled()
})