Jest + React JS компонент тестирования - PullRequest
0 голосов
/ 01 февраля 2019

Я только знакомлюсь с тестированием, и у меня есть небольшая проблема.Я пытаюсь проверить функции компонента, которые меняют состояние и вызывают функции документа.В документации Jest и Enzyme я не нашел правильного примера.Вот пример кода:

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>
        );
    }
}

Как проверить функции, которые получают и изменяют состояние и вызывают document.addEventListener?Пожалуйста помоги.

ОБНОВЛЕНИЕ> Тесты, которые я уже писал:

describe('tests of component', () => {
  test('Component renders correctly with isEditing=false', () => {
    const component = renderer
      .create(<EditableText children="I'm text in EditableText" />)
      .toJSON();
    expect(component).toMatchSnapshot();
  });

  test('Component changes to isEditing=true when clicked on it', () => {
    const component = renderer
      .create(<EditableText />);

    let tree = component.toJSON();
    tree.props.onClick();
    tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });

});

describe('tests of logic', () => {
  test.only('OnClick should change state and add event listeners', ()=> {
    const state = { isEditing: false, currentValue: null }
    global.document.addEventListener = jest.fn();
    EditableText.onClick(() => {
      expect(global.document.addEventListener).toHaveBeenCalled();
    });;
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...