提问人:Roma N 提问时间:6/19/2023 更新时间:6/19/2023 访问量:72
如何使用 react 测试库测试 e.stopPropagation?
how to test e.stopPropagation with react testing library?
问:
在旧项目中,我有用于收听键的 react 类组件。我尝试编写 100% 覆盖率测试,但我不明白如何调用e.isPropagationStopped
详细:
// my class component
class KeyListener extends Component {
handleKeyDown = (e) => {
if (e.isPropagationStopped && e.isPropagationStopped()) {
console.log('THERE')
return
}
}
componentDidMount() {
window.addEventListener('keydown', this.handleKeyDown, false)
}
render () {
return null
}
}
我的笑话不是 100% 覆盖率示例 (react-testing-library)
import { Provider } from 'react-redux';
import { HashRouter } from 'react-router-dom';
import configureStore from 'redux-mock-store';
import thunkMiddleware from 'redux-thunk';
import { render, screen, fireEvent } from '@testing-library/react';
import KeyListener from './KeyListener';
const mockStore = configureStore([thunkMiddleware]);
const store = mockStore({});
describe('test KeyListener', () => {
test('test', () => {
const keyButtonA = {
key: 'a',
keyCode: 65,
which: 65,
code: 'keyButtonA',
location: 0,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
};
render(
<Provider store={store}>
<HashRouter>
<>
<button
onKeyDown={(e) => {
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
}}
/>
<KeyListener keyCode={keyButtonA.keyCode} onKeyDown={() => {}} />
</>
</HashRouter>
</Provider>,
);
const button = screen.getByRole('button');
fireEvent.keyDown(button, keyButtonA);
expect(button).toBeInTheDocument();
});
});
您需要在此测试中编写什么才能 100% 覆盖它,或者更确切地说,调用控制台.log('THERE')?
答: 暂无答案
上一个:参考电流仅在类组件中就绪
评论