簡體   English   中英

單元測試 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)
})

我試過了:

  • 通過wrapper.html()發送
  • .find一個節點並發送(不模擬event.target
  • .simulate click里面的一個元素(不觸發事件監聽器)

我確定我遺漏了一些小東西,但我在任何地方都找不到這樣的例子。

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上這個酶問題的解決方案。

選擇的答案沒有覆蓋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()
})

我找到了可以避免使用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'));

使用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(); 
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM