javascript - 在 React 组件之外测试 mousedown 事件 : Jest + Enzyme

标签 javascript reactjs jestjs enzyme

我想使用 Jest 和 Enzyme 编写一个测试,测试具有事件监听器的组件,这样当给定 html 元素外部发生 mousedown 事件时,就会发生更改(在本例中,状态值被切换) 。我正在使用 jest 来模拟事件监听器并模拟 mousedown 事件,但是,当我尝试运行此测试时,我收到以下错误消息:

TypeError: Failed to execute 'contains' on 'Node': parameter 1 is not of type 'Node'.

显然我认为<div />当我使用 map.mousedown({ target: <section /> }); 模拟 mousedown 事件时,这不是我应该提供的正确值。如何正确模拟组件外部发生的 mousedown 事件?您可以看到下面的代码。谢谢!

sampleComponent.jsx:

import * as React from 'react';

const SampleComponent = () => {
  const [state, setState] = React.useState(false);
  const ref = React.useRef(null);

  const handleClickOutside = (event) => {
    if (
      !ref.current.contains(event.target)
    ) {
      setState(true);
    }
  };

  React.useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  });

  return (
    <div
      id="sample-div"
      ref={ref}
    >
      {`State value is: ${state}`}
    </div>
  );
};

export default SampleComponent;

sampleComponent.test.jsx:

import * as React from 'react';
import { mount } from 'enzyme';
import SampleComponent from './sampleComponent';

const setup = () => mount(<SampleComponent />);

test('testing mousedown', () => {
  const map = {};
  document.addEventListener = jest.fn((event, callback) => {
    map[event] = callback;
  });
  const wrapper = setup();
  expect(wrapper.find('#sample-div').text()).toBe('State value is: false');
  map.mousedown({ target: <section /> });
  expect(wrapper.find('#sample-div').text()).toBe('State value is: true');
});

最佳答案

您无法将 React JSX 作为 event.target 的值传递。由于您使用 document.addEventListener,因此它是 native DOM 事件。您需要传递一个 native DOM,例如 document.createElement('a')

以下是您的示例的测试用例:

sampleComponent.tsx:

import React from 'react';

const SampleComponent = () => {
  const [state, setState] = React.useState(false);
  const ref = React.useRef(null);

  const handleClickOutside = event => {
    if (!(ref.current as any).contains(event.target)) {
      setState(true);
    }
  };

  React.useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  });

  return (
    <div id="sample-div" ref={ref}>
      {`State value is: ${state}`}
    </div>
  );
};

export default SampleComponent;

sampleComponent.test.tsx:

import React from 'react';
import { mount } from 'enzyme';
import SampleComponent from './sampleComponent';
import { act } from 'react-dom/test-utils';

const setup = () => mount(<SampleComponent />);

beforeEach(() => {
  jest.resetAllMocks();
});
test('testing mousedown - 1', () => {
  const map: any = {};
  document.addEventListener = jest.fn((event, callback) => {
    map[event] = callback;
  });
  const wrapper = setup();
  expect(wrapper.find('#sample-div').text()).toBe('State value is: false');
  act(() => {
    map.mousedown({ target: document.createElement('a') });
  });
  expect(wrapper.find('#sample-div').text()).toBe('State value is: true');
  expect(document.addEventListener).toBeCalledTimes(2);
});

test('testing mousedown - 2', () => {
  const map: any = {};
  document.addEventListener = jest.fn((event, callback) => {
    map[event] = callback;
  });
  const wrapper = setup();
  expect(wrapper.find('#sample-div').text()).toBe('State value is: false');
  act(() => {
    map.mousedown({ target: wrapper.getDOMNode() });
  });
  expect(wrapper.find('#sample-div').text()).toBe('State value is: false');
  expect(document.addEventListener).toBeCalledTimes(1);
});

100%覆盖率的单元测试结果:

PASS  src/stackoverflow/58610112/sampleComponent.test.tsx (8.041s)
  ✓ testing mousedown - 1 (46ms)
  ✓ testing mousedown - 2 (3ms)

---------------------|----------|----------|----------|----------|-------------------|
File                 |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------------|----------|----------|----------|----------|-------------------|
All files            |      100 |      100 |      100 |      100 |                   |
 sampleComponent.tsx |      100 |      100 |      100 |      100 |                   |
---------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.5s

关于javascript - 在 React 组件之外测试 mousedown 事件 : Jest + Enzyme,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58610112/

相关文章:

css - 如何在 MUI 中应用自定义动画效果@keyframes?

javascript - 重置 React 中控件的默认值

javascript - 如何断言一个函数是从另一个函数中调用的?

vue.js - 用 jest : $route is always undefined 进行 Vue 测试

javascript - 测试组件快照,获取 json 错误

javascript - 避免在 jQuery 内联 css 中使用双引号

javascript - 在mvc中调用带有jquery参数的url

javascript - 如何在Konva中设置文本的 `underline`?

javascript - meteor :强制渲染元素

ajax - [React]将异步数据获取到组件中的不同方式