我正在使用Jest为React Components编写测试。我无法修复组件测试中的bug。我尝试将焦点添加到测试代码的元素上:
await waitFor(() => expect(screen.getByTestId('continue')).toHaveFocus());
但是没有成功,如何解决这个错误?
这是组件代码:
function SuccessCommentAddPopup({onSuccessComment}: SuccessCommentAddPopupProps): JSX.Element {
return (
<AriaModal
titleText='add comment success'
initialFocus="#continue"
>
<div style={{position: 'relative', width: '550px', height: '410px', marginBottom: '50px'}}>
<div className={style.modal}>
<div className={style.modalWrapper}>
<div className={style.modalOverlay} data-close-modal></div>
<div className={style.modalContent}>
<svg className={style.modalIcon} width="26" height="20" aria-hidden="true">
<use xlinkHref="#icon-success"></use>
</svg>
<p className={style.modalMessage}>Thank's a lot!</p>
<div className={style.modalButtonContainer}>
<button
id='continue'
data-testid='continue'
className={style.modalButton}
onClick={()=>{
onSuccessComment(false);
}}
>
Close
</button>
</div>
<button
className={style.modalCloseBtn}
type="button"
aria-label="Close"
onClick={()=>{
onSuccessComment(false);
}}
>
<span className={style.buttonCrossIcon}>
</span><span className={style.modalCloseBtninteractiveArea}></span>
</button>
</div>
</div>
</div>
</div>
</AriaModal>
);
}
export default SuccessCommentAddPopup;
这是测试代码:
const history = createMemoryHistory();
history.push('/guitars/1');
describe('Component: SuccessCommentAddPopup', () => {
it('Компонент отрисовывается корректно', async () => {
render(
<HistoryRouter history={history}>
<SuccessCommentAddPopup
onSuccessComment={jest.fn()}
/>
</HistoryRouter>,
);
await waitFor(() => expect(screen.getByTestId('continue')).toHaveFocus());
expect(screen.getByText('Спасибо за ваш отзыв!')).toBeInTheDocument();
});
});
2条答案
按热度按时间wrrgggsh1#
您需要模拟
tabbable
模块。请检查此链接3b6akqbq2#
@Ararat is correct. I solved this by mocking out tabbable: https://github.com/focus-trap/tabbable#testing-in-jsdom
添加了./mocks/tabable. js,并添加了以下内容:
我花了很多时间来弄清楚这一点,这就是我分享的原因!我在一个vue 3项目中使用@vueUs的useFocusTrap,我的vue测试库组件测试因为这个缺失而中断!