Unit testing React click outside component

2020-02-26 04:01发布

Using the code from this answer to solve clicking outside of a 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
    }
}

I can't figure out how to unit test the unhappy path so the alert isn't run, what i've got so far:

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)
})

I've tried:

  • sending through wrapper.html()
  • .finding a node and sending through (doesn't mock a event.target)
  • .simulateing click on an element inside (doesn't trigger event listener)

I'm sure i'm missing something small but I couldn't find an example of this anywhere.

3条回答
做自己的国王
2楼-- · 2020-02-26 04:14

Use sinon to track the handleClickOutside is called or not. By the way, I just now released our project where I need this unit-test in the Nav component . Indeed when you click outside, all submenus should be closed.

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(); 
})
查看更多
贪生不怕死
3楼-- · 2020-02-26 04:18

The selected answer did not cover the else path of handleClickOutside

I added mousedown event on ref element to trigger else path of 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()
})
查看更多
家丑人穷心不美
4楼-- · 2020-02-26 04:31
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()
})

The solution from this enzyme issue on github.

查看更多
登录 后发表回答