模拟键盘事件和测试stopImmediatePropagation被React调用



我有一个功能组件,它具有handleKeyDown功能:

const handleKeyDown = () => {
if (e.key === 'Backspace') {
e.nativeEvent.stopImmediatePropagation()
}
}
return (
<input onKeyDown={handleKeyDown} //etc />
)

我如何测试BACKSPACE,e.nativeEvent.stopImmediatePropagation被调用?

我正在使用酶/反应测试库和jest。

任何指导将不胜感激!

对于enzyme,您可以通过在浅包装器上使用.simulate(event[,…args])来模拟keydown事件。创建一个模拟的keydown事件对象并将其传递给.simulate()方法。

index.tsx:

import React from 'react';
export function App() {
const handleKeyDown = (e) => {
if (e.key === 'Backspace') {
e.nativeEvent.stopImmediatePropagation();
}
};
return <input onKeyDown={handleKeyDown} />;
}

index.test.tsx:

import { shallow } from 'enzyme';
import React from 'react';
import { App } from './';
describe('68566755', () => {
test('should pass', () => {
const wrapper = shallow(<App />);
const mEvent = {
key: 'Backspace',
nativeEvent: { stopImmediatePropagation: jest.fn() },
};
wrapper.simulate('keydown', mEvent);
expect(mEvent.nativeEvent.stopImmediatePropagation).toBeCalledTimes(1);
});
});

测试结果:

PASS  examples/68566755/index.test.tsx (8.625 s)
68566755
✓ should pass (5 ms)
-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |       50 |     100 |     100 |                   
index.tsx |     100 |       50 |     100 |     100 | 5                 
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.174 s, estimated 10 s

最新更新