使用酶测试React组件状态的变化并监视实例方法

vam*_*olu 13 javascript sinon reactjs enzyme chai-enzyme

我正在开发一个包装器组件,用于在React中平滑地加载图像.我使用含有mocha,chai和sinon的酶对我的组件进行单元测试.在这里的测试中,我试图测试:

  1. 加载图像时更新组件的状态

  2. onLoad调用组件上的实例方法

const wrapper = shallow( );

const onLoad = wrapper.find('img').props().onLoad;
const onLoadSpy = sinon.spy(onLoad); wrapper.update();
const status = wrapper.state().status;
expect(onLoadSpy).to.have.been.called;
expect(status).to.equal('LOADED');

我发现状态更新既不会被酶反映,也不会更新onLoad间谍的通话计数.这是测试的相应代码:

export default class Image extends Component {
  constructor(props) {
    super(props);
    if (props.src != null && typeof props.src === 'string') {
      this.state = {
        status: LOADING,
      };
    } else {
      this.state = {
        status: PENDING,
      };
    }
    this.onLoad = this.onLoad.bind(this);
  }

  onLoad() {
    this.setState({
      status: LOADED,
    });
  }

  render() {
    //lots of code above the part we care about
    const defaultImageStyle = style({
      opacity: 0,
      transisition: 'opacity 150ms ease',
    });

    const loadedImageStyle = style({
      opacity: 1,
    });

    let imageStyle = defaultImageStyle;

    if (this.state.status === LOADED) {
      imageStyle = merge(defaultImageStyle, loadedImageStyle);
    } else {
      imageStyle = defaultImageStyle;
    }


    let image;
    if (alt != null) {
      image = (<img
        className={imageStyle}
        src={src}
        width={width}
        height={height}
        alt={alt}
        onLoad={this.onLoad}
      />);
    } else {
      image = (<img
        className={imageStyle}
        src={src}
        width={width}
        height={height}
        role="presentation"
        onLoad={this.onLoad}
      />);
    }

    let statusIndicator = null;
    if (this.state.status === LOADING) {
      statusIndicator = (<div className={loadingStyle}></div>);
    }

    return (<div className={wrapperStyle}>
      {statusIndicator}
      {image}
    </div>);

    }}
Run Code Online (Sandbox Code Playgroud)

要查看完整代码以获得更好的上下文:

vam*_*olu 16

人们可以不依靠测试此sinon.通过期望调用onLoadonFire事件侦听器,测试检查是否img触发loaderror事件.

相反,simulate img使用enzyme并检查发生适当状态转换的事件:

it('has a state of LOADED if a good src prop is supplied', () => {
  const wrapper = shallow(<Image 
    src="anyString.jpg"
    width={300}
    height={300}
  />);

  const img = wrapper.find('img');
  img.simulate('load');
  const status = wrapper.state().status;
  expect(status).to.equal('LOADED');
});
Run Code Online (Sandbox Code Playgroud)

这也消除了mount对组件的需要.更新的测试可以在这里找到.