如何在构造函数中通过创建新事件对组件进行单元测试?

时间:2018-08-31 09:20:27

标签: javascript reactjs enzyme

我有一个正在创建新事件的组件,该事件将在组件更新时分派。

 export class FullScreenButton extends Component {
  /**
   * @constructor
   * Instanciates a new Event called resize and binds the current context to the handleClick method.
   */
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
    this.event = new Event('resize')
  }

  /**
   * If the component was updated then dispatches the resize event.
   * @param {Object} prevProps - Previous state of the props.
   */
  componentDidUpdate(prevProps) {
    if (prevProps !== this.props) {
      window.dispatchEvent(this.event);
    }
  }
  ...
}

但是,在单元测试中,当使用酶安装组件时,它向我显示此错误:

1) Testing FullScreenButton Component
       Should alter the state and css on click:
     ReferenceError: Event is not defined

我想念什么? 我在这里先向您的帮助表示感谢!

编辑:我的测试如下:

import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';

import { FullScreenButton } from '../../../../../src/screens/flowConstructor/components/toolsMenu/FullScreenButton';

describe.only('Testing FullScreenButton Component', () => {
  it('Should alter the state and css on click', (done) => {
    const wrapper = mount(<FullScreenButton />);
    wrapper.setProps({
      toggleFullScreen: (fullscreen) => {
        expect(fullscreen).to.equal(false);
      }
    });


    expect(wrapper.find('button').hasClass('gof-icon-full-screen')).to.equal(true);
    wrapper.find('button').simulate('click');
    expect(wrapper.find('button').hasClass('gof-icon-full-windowed')).to.equal(true);
    done();
  });
});

更新:找到了一个可行的解决方案。 这是更新的测试:

describe.only('Testing FullScreenButton Component', () => {
  before(() => {
    global.Event = class {
      constructor(event) {
        console.log(event);
      }
    };

    global.window.dispatchEvent = (event) => {
      console.log(event)
    };
  });

  it('Should alter the state and css on click', (done) => {
    const wrapper = mount(<FullScreenButton />);
    wrapper.setProps({
      toggleFullScreen: () => {},
      fullScreen: false,
    });

    expect(wrapper.find('span').hasClass('gof-icon-full-screen')).to.equal(true);
    wrapper.setProps({
      fullScreen: true,
    });
    expect()
    expect(wrapper.find('span').hasClass('gof-icon-windowed')).to.equal(true);
    done();
  });
});

0 个答案:

没有答案