vendredi 1 février 2019

Jest + React JS testing component

I am just getting acquainted with testing and I have a little problem. I'm trying to test the functions of a component that change state and call functions of a document. In the documentation of Jest and Enzyme, I did not find the right example. Here is a sample code:

class EditableText extends React.PureComponent {
constructor(props) {
    super(props);
    this.state = {
        isEditing: false,
        currentValue: null
    };
    this.textAreaRef = React.createRef();
}
onClick = () => {
    if (!this.state.isEditing) {
        this.setState({ isEditing: true });
        setTimeout(() => {
            this.textAreaRef.current.focus();
        }, 100);
        document.addEventListener('keydown', this.onKeyDown);
        document.addEventListener('click', this.onOutsideClick);
    }
};
onOutsideClick = e => {
    if (e.target.value !== this.state.currentValue) {
        this.closeEditMode();
    }
};
closeEditMode() {
    this.setState({ isEditing: false });
    document.removeEventListener('keydown', this.onKeyDown);
    document.removeEventListener('click', this.onOutsideClick);
}
onKeyDown = e => {
    if (e.code === 'Enter') {
        this.onUpdateValue();
    } else if (e.code === 'Escape') {
        this.closeEditMode();
    }
};
onUpdateValue = () => {
    this.props.onSubmit(this.state.currentValue || this.props.value);
    this.closeEditMode();
};
render() {
    const { isEditing, currentValue } = this.state;
    const { value } = this.props;
    return isEditing ? (
        <TextArea
            className="editable-text__textarea"
            ref={this.textAreaRef}
            onClick={this.onClick}
            value={currentValue === null ? value || '' : currentValue}
            onChange={(_e, { value }) => this.setState({ currentValue: value })}
        />
    ) : (
            <div className="editable-text__readonly" onClick={this.onClick}>
                <div>{this.props.children}</div>
                <div className="editable-text__icon-container">
                    <Icon name="edit" className="editable-text__icon" />
                </div>
            </div>
        );
    }
}

How to test functions, that receive and change state and calls document.addEventListener? Please, help.

Aucun commentaire:

Enregistrer un commentaire