0

我有 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 |
4

2 回答 2

1

考虑 fireEvent.click,它创建一个 click 事件并在给定的 DOM 节点上调度该事件。这适用于大多数情况下,当您只想测试单击元素时会发生什么,但是当用户实际单击您的元素时,这些是通常触发的事件(按顺序):

fireEvent.mouseOver(element)
fireEvent.mouseMove(element)
fireEvent.mouseDown(element)
element.focus() (if that element is focusable)
fireEvent.mouseUp(element)
fireEvent.click(element)

看看这篇博文 https://testing-library.com/docs/guide-events/

于 2021-06-14T20:49:46.590 回答
0

首先,这行对我来说似乎很奇怪您如何导入 Signup 组件:import Signup from '.';

但我也认为你应该通过render(<Signup show={true}/>);以呈现模式并能够聚焦输入,因为只有浏览器上的可见元素是可聚焦的

于 2021-06-14T20:58:31.147 回答