首页 热点资讯 义务教育 高等教育 出国留学 考研考公

如何进行React组件单元测试

发布网友 发布时间:2022-04-26 09:12

我来回答

1个回答

热心网友 时间:2022-04-22 16:05

// React源码
// Link.react.js
import React from 'react';

const STATUS = {
NORMAL: 'normal',
HOVERED: 'hovered',
};

export default class Link extends React.Component {

constructor() {
super();

this._onMouseEnter = this._onMouseEnter.bind(this);
this._onMouseLeave = this._onMouseLeave.bind(this);

this.state = {
class: STATUS.NORMAL,
};
}

_onMouseEnter() {
this.setState({class: STATUS.HOVERED});
}

_onMouseLeave() {
this.setState({class: STATUS.NORMAL});
}

render() {
return (
<a
className={this.state.class}
href={this.props.page || '#'}
onMouseEnter={this._onMouseEnter}
onMouseLeave={this._onMouseLeave}>
{this.props.children}

);
}

}

// 测试代码
// Link.react-test.js
import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';

test('Link changes the class when hovered', () => {
const component = renderer.create(
*
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();

// manually trigger the callback
tree.props.onMouseEnter();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();

// manually trigger the callback
tree.props.onMouseLeave();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
-

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com