关于redux容器的单元测试用例实现



如何为给定容器编写单元测试用例,该容器与下面给出的组件相关联?这里的PopupNotification.jsx是一个组件文件,它将PopupNotification.js作为容器文件。我想要一个容器文件的jest单元测试用例实现。

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

我建议使用redux模拟商店来获得对商店的完全控制。然后你可以做之类的事情

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

从他们的文档复制

由于这是一个单元测试,您只需要测试这个容器负责什么,并且从您的示例中可以看出,它暴露了redux连接的组件,因此您应该测试您的mapStateToProps&CCD_ 2正在正确执行。

相关内容

  • 没有找到相关文章

最新更新