我有 react-bootstrap 的 Modal 组件,它有一个输入,当我对 Focus 进行单元测试时,它说它收到了整个文档,而不仅仅是 Input 元素。
有谁知道为什么焦点转到整个文档(Modal 是否使整个文档集中)。非常感谢您的帮助。下面是我的代码
注册.js
import { Container, Form, Modal } from 'react-bootstrap';
const Signup = () => {
const handleClick = (e) => {
e.preventDefault();
const element = e.currentTarget;
const id = element.getAttribute('id');
if (id === 'userEmail') {
const emailLabel = document.getElementById('emailLabel');
emailLabel.style.fontSize = '30px';
}
};
return (
<Container>
<Modal show={true} autoFocus>
<Modal.Header>Header</Modal.Header>
<Modal.Body>
<Form>
<Form.Group>
<Form.Label>
<span id="emailLabel">Email</span>
<Form.Control
name="userEmail"
id="userEmail"
data-testid="userEmail"
type="email"
onClick={(e) => handleClick(e)}
/>
</Form.Label>
</Form.Group>
</Form>
</Modal.Body>
</Modal>
</Container>
);
};
export default Signup;
Signup.test.js
import Signup from '.';
describe('helo', () => {
it('signup', async () => {
render(<Signup />);
const emailInput = screen.getByTestId('userEmail');
fireEvent.click(emailInput);
expect(emailInput).toHaveFocus();
});
});
结果
Expected element with focus:
<input class="form-control" data-testid="userEmail" id="userEmail" name="userEmail" type="email" />
Received element with focus:
<div aria-modal="true" class="fade modal show" role="dialog" style="display: block;" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header">Header</div><div class="modal-body"><form class=""><div class="form-group"><label class="form-label"><span id="emailLabel" style="font-size: 30px;">Email</span><input class="form-control" data-testid="userEmail" id="userEmail" name="userEmail" type="email" /></label></div></form></div></div></div></div>
123 | const emailInput = screen.getByTestId('userEmail');
124 | fireEvent.click(emailInput);
> 125 | expect(emailInput).toHaveFocus();
| ^
126 | });
127 | });
128 |