Относительно реализации юнит-теста в шутке для редукционных контейнеров - PullRequest
0 голосов
/ 21 апреля 2020

Как написать пример модульного теста для данного контейнера, который связан с компонентом, указанным ниже? Здесь PopupNotification.jsx - это файл компонента, который имеет PopupNotification. js в качестве файла контейнера. Мне нужна реализация юнит-тестового примера для файла контейнера.

PopupNotification.jsx -> файл компонента

import React from "react";
import PropTypes from "prop-types";

import { notyIcons, notyTimeout } from "../helpers/constants";

class PopupNotification extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showNoty: props.showNoty
    };

    this.notyTimer = null;
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    return {
      showNoty: nextProps.showNoty
    };
  }

  shouldComponentUpdate() {
    return true;
  }

  startNotyTimer() {
    let __self = this;

    if (this.notyTimer) {
      clearTimeout(this.notyTimer);
    }

    this.notyTimer = setTimeout(function() {
      __self.closeNoty();
    }, notyTimeout);
  }

  componentWillUnmount() {
    if (this.notyTimer) {
      clearTimeout(this.notyTimer);
    }

    this.setState({ showNoty: false });
  }

  closeNoty() {
    let { id } = this.props;

    this.props.clearNotification(id);
    this.setState({
      showNoty: false
    });
  }

  getNotyIcon() {
    return <i className={`notification-popup__icon pos-l-m ${notyIcons[this.props.type]}`} />;
  }

  getNotyLayout() {
    let notyIcon = this.getNotyIcon();
    let { message: notyMessage, type } = this.props;

    return (
      <div className={`pure-g notification-popup ${type}`}>
        <div className="pure-u-1-8 pos">{notyIcon}</div>
        <div className="pure-u-7-8">
          <div className="u-margin-8--left">{notyMessage}</div>
        </div>
      </div>
    );
  }

  render() {
    var notyLayout = null;

    if (this.state.showNoty) {
      this.startNotyTimer();
      notyLayout = this.getNotyLayout();
    }

    return notyLayout;
  }
}

PopupNotification.propTypes = {
  message: PropTypes.string,
  type: PropTypes.string,
  id: PropTypes.number,
  showNoty: PropTypes.bool,
  clearNotification: PropTypes.func
};

PopupNotification.defaultProps = {
  message: "",
  type: ""
};

export default PopupNotification;

PopupNotification. js -> файл контейнера

import { connect } from "react-redux";
import { actions } from "../ducks/common";

import PopupNotification from "../components/PopupNotification";

const mapStateToProps = state => {
  let { common: { popupNotifications = [] } } = state;
  let showNoty = false;
  if (popupNotifications.length) {
    showNoty = true;
  }

  return {
    showNoty,
    ...popupNotifications[popupNotifications.length-1]
  };
};

const mapDispatchToProps = dispatch => {
  return {
    clearNotification: notyId => {
      dispatch(actions.clearPopupNotification({id: notyId}));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PopupNotification);

1 Ответ

0 голосов
/ 21 апреля 2020

Я предлагаю использовать redux-mock-store , чтобы получить полный контроль над вашим магазином. Затем вы можете делать такие вещи, как

const actions = store.getActions()
expect(actions).toEqual([expectedPayload])

Скопировано из их документов

Поскольку это модульный тест, вам просто нужно проверить, за что отвечает этот контейнер, и из того, что я вижу из вашего примера, он показывает компонент, подключенный к редуксу, поэтому вы должны проверить, что ваши mapStateToProps & mapDispatchToProps работают правильно.

...