gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:30:18 26 4
gpt4 key购买 nike

我想使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com