单元测试 React 单击组件​​外

IT技术 javascript unit-testing reactjs jestjs enzyme
2021-04-24 05:32:51

使用此答案中的代码解决在组件外部单击的问题:

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

我试过了:

  • 通过发送 wrapper.html()
  • .finding 一个节点并发送(不模拟 a event.target
  • .simulateingclick内部元素(不触发事件侦听器)

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

4个回答
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()
})

github上这个酶问题的解决方案

选择的答案没有覆盖else路径 handleClickOutside

我在 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()
})

我找到了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"

最简单的事情就是在身体上 dispatchEvent

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