这是我的组件。它基本上是另一个组件的包装器。我的问题是我该如何对这个组件进行单元测试?除了检查状态并调用这两种方法并确保它们更新状态。
除此之外,这似乎只是渲染道具/状态所以有没有必要对此进行测试?
import React from 'react';
import { PropTypes as PT } from 'prop-types';
export default Wrapped =>
class extends React.Component {
static propTypes = {
numOne: PT.number,
};
constructor(props) {
super(props);
this.state = {
showModal: false,
};
}
openModal = () => {
this.setState({
showModal: true,
});
};
closeModal = () => {
this.setState({
showModal: false,
});
};
render() {
return (
<Wrapped
numberValue={this.props.numOne}
showHolidayModal={this.state.showHolidayListModal}
showModal={this.openModal}
closeModal={this.closeModal}
{...this.props}
/>
);
}
};
这是我的组件(只是示例)我也是单元测试,它呈现传入的内容
import React from 'react';
import { PropTypes as PT } from 'prop-types';
import container from './container';
import { Card, Button, Modal } from '../common';
export const Leave = props => {
return (
<div>
<span>Dummy data : {props.numberValue}</span>
{props.showModal && <Modal />}
<Button onClick={props.closeModal} label="close" />
</div>
);
};
Leave.propTypes = {
numberValue: PT.number,
showModal: PT.bool,
openModal: PT.func,
closeModal: PT.func,
};
export default container(Leave);
答案 0 :(得分:2)
可能是这样的。您应该测试包装器以使用其道具呈现Wrapped组件。还要测试更新状态的函数。
const Bar = props => <span />
const Test = container(Bar)
const wrapper = shallow(<Test prop1={1} prop2={2}>)
const bar = wrapper.find(Bar)
expect(bar).to.have.length(1)
expect(bar.props()).contains({ prop1: 1, prop2: 2})
bar.props().showModal()
expect(wrapper.state().showModal).to.be(true)