D
D
Denis2018-07-05 11:32:31
JavaScript
Denis, 2018-07-05 11:32:31

Can't figure out how to simulate the keyUp event in Jest?

Hello. I'm trying to write tests in Jest. Faced the problem of describing the keyUp event. Tell me what's wrong in my
React test:

state = {
        tabFocused: false
    };

onKeyUp = (e: SyntheticKeyboardEvent<HTMLElement>) => {
        if (
            e.keyCode === KEY_CODES.TAB &&
            document.activeElement === this.input
        ) {
            this.setState(() => ({
                tabFocused: true
            }));
        }
    };

render() {

        return (
            <label onKeyUp={this.onKeyUp}>
                <span>
                    <input
                        disabled={disabled}
                        type="checkbox"
                        checked={value}
                        id={id}
                        name={name}
                        className={sn('toggle__input')}
                        onChange={({target: {checked}}) => onChange(checked)}
                        onFocus={onFocus}
                        onBlur={this.onBlur}
                        ref={this.withRef}
                    />
                </span>
            </label>
        );
    }

test:
import React from 'react';
import {shallow, mount} from 'enzyme';
import {Input} from '../../src';

test('calls onKeyUp', () => {
        const wrapper = shallow(<Input.Toggle id="toggle" name="test-toggle" />);
        expect(wrapper.state().tabFocused).toBe(false);
        wrapper.find('.toggle').simulate('keyUp', {keyCode: 9});
        expect(wrapper.state().tabFocused).toBe(true);
    });

5b3dd79a6ab94659347656.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aleksei Podgaev, 2018-07-12
@alexiusp

enzyme, which you apparently use (jest has nothing to do with it) does not simulate browser events. it simply invokes the specified event handler bound to the found element. Your handler is attached to the label, so you need to look for it to start simulate. you are looking for, as I understand it, input and trying to call simulate from it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question