单元测试 React 点击外部组件

Unit testing React click outside component

使用 中的代码解决组件外部的点击问题:

componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
}

componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
}

setWrapperRef(node) {
    this.wrapperRef = node;
}

handleClickOutside(event) {
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
        this.props.actions.something() // Eg. closes modal
    }
}

我不知道如何对不愉快的路径进行单元测试,所以警报不是 运行,到目前为止我得到的是:

it('Handles click outside of component', () => {
  props = {
    actions: {
      something: jest.fn(),
    }
  }
  const wrapper = mount(
    <Component {... props} />,
  )
  expect(props.actions.something.mock.calls.length).toBe(0)

  // Happy path should trigger mock

  wrapper.instance().handleClick({
    target: 'outside',
  })

  expect(props.actions.something.mock.calls.length).toBe(1)  //true

  // Unhappy path should not trigger mock here ???

  expect(props.actions.something.mock.calls.length).toBe(1)
})

我试过:

我确定我遗漏了一些小东西,但我在任何地方都找不到这样的例子。

使用sinon跟踪handleClickOutside是否被调用。顺便说一下,我刚刚发布了我们的项目,我需要在 Nav 组件中进行单元测试。实际上,当您在外部单击时,所有子菜单都应关闭。

import sinon from 'sinon';
import Component from '../src/Component';

it('handle clicking outside', () => {
     const handleClickOutside = sinon.spy(Component.prototype, 'handleClickOutside');
     const wrapper = mount(
         <div> 
           <Component {... props} />
           <div><a class="any-element-outside">Anylink</a></div>
         </div>
      ); 

      wrapper.find('.any-element-outside').last().simulate('click'); 
      expect(handleClickOutside.called).toBeTruthy(); 
      handleClickOutside.restore(); 
})
import { mount } from 'enzyme'
import React from 'react'
import ReactDOM from 'react-dom'

it('Should not call action on click inside the component', () => {
  const map = {}

  document.addEventListener = jest.fn((event, cb) => {
    map[event] = cb
  })

  const props = {
    actions: {
      something: jest.fn(),
    }
  }

  const wrapper = mount(<Component {... props} />)

  map.mousedown({
    target: ReactDOM.findDOMNode(wrapper.instance()),
  })

  expect(props.actions.something).not.toHaveBeenCalled()
})

this 酶问题的解决方案 github。

选择的答案没有覆盖handleClickOutside

的else路径

我在 ref 元素上添加了 mousedown 事件以触发 handleClickOutside

的其他路径
import { mount } from 'enzyme'
import React from 'react'
import ReactDOM from 'react-dom'

it('Should not call action on click inside the component', () => {
  const map = {}

  document.addEventListener = jest.fn((event, cb) => {
    map[event] = cb
  })

  const props = {
    actions: {
      something: jest.fn(),
    }
  }
  //test if path of handleClickOutside
  const wrapper = mount(<Component {... props} />)

  map.mousedown({
    target: ReactDOM.findDOMNode(wrapper.instance()),
  })

  //test else path of handleClickOutside
  const refWrapper = mount(<RefComponent />)

  map.mousedown({
    target: ReactDOM.findDOMNode(refWrapper.instance()),
  })

  expect(props.actions.something).not.toHaveBeenCalled()
})

我发现 case/solution 可以避免使用 ReactDOM.findDOMNode。对待下面的例子:

import React from 'react';
import { shallow } from 'enzyme';

const initFireEvent = () => {
  const map = {};

  document.addEventListener = jest.fn((event, cb) => {
    map[event] = cb;
  });

  document.removeEventListener = jest.fn(event => {
    delete map[event];
  });

  return map;
};

describe('<ClickOutside />', () => {
  const fireEvent = initFireEvent();
  const children = <button type="button">Content</button>;

  it('should call actions.something() when clicking outside', () => {
    const props = {
      actions: {
       something: jest.fn(),
     }
    };

    const onClick = jest.fn();

    mount(<ClickOutside {...props}>{children}</ClickOutside>);
    fireEvent.mousedown({ target: document.body });

    expect(props.actions.something).toHaveBeenCalledTimes(1);
  });

  it('should NOT call actions.something() when clicking inside', () => {
    const props = {
      actions: {
       something: jest.fn(),
     }
    };

    const wrapper = mount(
      <ClickOutside onClick={onClick}>{children}</ClickOutside>,
    );

    fireEvent.mousedown({
      target: wrapper.find('button').instance(),
    });

    expect(props.actions.something).not.toHaveBeenCalled();
  });
});

版本:

"react": "^16.8.6",
"jest": "^25.1.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2"

最简单的事情就是在 body 上发送事件

  mount(<MultiTagSelect {...props} />);
window.document.body.dispatchEvent(new Event('click'));