gpt4 book ai didi

javascript - 使用 enzyme 进行 react 测试 react chop

转载 作者:行者123 更新时间:2023-11-28 20:22:10 25 4
gpt4 key购买 nike

我正在使用 react-truncate对于一个项目。带有展开折叠和省略号的基本设置应该是这样的:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Truncate from 'react-truncate';

class ReadMore extends Component {
constructor(...args) {
super(...args);

this.state = {
expanded: false,
truncated: false
};

this.handleTruncate = this.handleTruncate.bind(this);
this.toggleLines = this.toggleLines.bind(this);
}

handleTruncate(truncated) {
if (this.state.truncated !== truncated) {
this.setState({
truncated
});
}
}

toggleLines(event) {
event.preventDefault();

this.setState({
expanded: !this.state.expanded
});
}

render() {
const {
children,
more,
less,
lines
} = this.props;

const {
expanded,
truncated
} = this.state;

return (
<div>
<Truncate
lines={!expanded && lines}
ellipsis={(
<span> <a href='#' onClick={this.toggleLines}>{more}</a></span>
)}
onTruncate={this.handleTruncate}
>
{children}
</Truncate>
{!truncated && expanded && (
<span> <a href='#' onClick={this.toggleLines}>{less}</a></span>
)}
</div>
);
}
}

ReadMore.defaultProps = {
lines: 3,
more: 'Read more',
less: 'Show less'
};

ReadMore.propTypes = {
children: PropTypes.node.isRequired,
text: PropTypes.node,
lines: PropTypes.number
};

export default ReadMore;

我想在我的项目中使用 enzyme 测试展开-折叠功能,到目前为止我可以验证基本设置和默认行为:

const wrapper = shallow(<ReadMore />); // where above code is defined
expect(wrapper.state('expanded')).to.equal(false); // passes

但是我对如何刺激 expand click 行为感到困惑,我试过了

wrapper.toggleLines;//返回未定义。

调试输出console.log(wrapper.debug());

<div>
<Truncate lines={3} ellipsis={{...}} onTruncate={[Function: bound handleTruncate]} trimWhitespace={false} />
</div>

我不确定如何访问 Read more span 的 onClick 属性

基本上我正在寻找的是这样的东西:

const wrapper = shallow(<ExpandCollapse />); // where above code is defined
expect(wrapper.state('expanded')).to.equal(false); // passes
//simulate onclick on Expand button
expect(wrapper.state('expanded')).to.equal(true); // should pass
//then trigger onclick on Collapse button
expect(wrapper.state('expanded')).to.equal(false); // should pass

关于如何继续进行的任何想法?提前致谢。

最佳答案

如果您的 onClick 目标是子组件/在子组件内,您将不得不使用 mount 代替,因为 shallow 仅呈现一层深。

例如,它可能是这样的:

const wrapper = mount(<Foo onClick={onClick} />); 
wrapper.find('span').simulate('click');

关于javascript - 使用 enzyme 进行 react 测试 react chop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48073514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com