Answer the question
In order to leave comments, you need to log in
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>
);
}
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);
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question