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

Mock keyboard event and test stopImmediatePropagation is called with React

我有一个具有 handleKeyDown 功能的功能组件:

const handleKeyDown = () => {
   if (e.key === 'Backspace') {
       e.nativeEvent.stopImmediatePropagation()
   }
}

return (
  <input onKeyDown={handleKeyDown} //etc />
)
   

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

我正在使用 enzyme/react-testing 库和 jest。

任何指导将不胜感激!

对于enzyme,您可以在shallow wrapper 上使用.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