我想在 Cypress 中测试递增和递减 HTML 输入字段 (type="number"
) 的值。更准确地说,我更喜欢使用箭头键来增加和减少值,但我似乎无法使用最明显的方法让它工作。
作为一个最小的工作示例,我设置了一个 React 组件,其渲染方法如下所示:
render() {
return (<input type="number" />);
};
在 Cypress 之外,在此字段中输入内容没有任何问题。使用箭头键和鼠标递增和递减值也是如此。
According to Cypress' API documentation on the .type-method , 可以使用所谓的特殊字符序列 {uparrow}
和 {downarrow}
作为 cy.type 的参数()
来模拟用户的上下按键。我已经尝试在输入标签和文档正文 ( in case the increment/decrement listeners are somehow defined globally ) 上使用这种方法,如下所示,但它似乎不起作用:
it('Increments the input value when the up key is pressed', () => {
cy.get('input').type('1000{uparrow}');
// Sets the value to 1000, but does not increment the value
cy.get('body').type('{uparrow}');
// Still at 1000. The event listener is not global after all.
cy.get('input').type('{selectall}{backspace}');
// Selecting all the input and deleting it
// using some of the other "special character sequences" works.
});
查看 Cypress 的控制台输出(下图),向上箭头键事件(键代码 38)显然是由 Cypress 发送的。不过,与常规按键相比,此按键触发的生命周期事件更少。
有人知道我可能做错了什么吗?或者我还能尝试什么?我对完全避免模拟按键的方法持开放态度,只要它们不涉及手动提取、递增和将值插入输入字段。
最佳答案
Cypress 在浏览器中工作,这意味着您的测试代码在浏览器中进行评估。这意味着任何在 JavaScript 中无法访问的东西也可能无法被 Cypress 访问——尽管支持 native 事件在 Cypress 的 roadmap 上。 .
当您使用 .type()
时在 Cypress 中,Cypress 会触发所有必要的事件来模拟该行为。使用数字输入的向上/向下箭头是浏览器特定的实现,并且需要 Cypress 的 native 事件支持才能正确实现。
也就是说,您可能只想测试单击向上/向下箭头时应用程序的行为(毕竟 - 您不需要测试数字是否上升和下降,因为这是浏览器实现)。单击向上和向下箭头时,将触发 change
事件,因此您基本上可以使用 .trigger()
测试单击向上/向下箭头时应用程序的行为。命令如下:
cy.get('input[type="number"]').type('1000').trigger('change')
关于javascript - 在 Cypress 中递增和递减 <input type ="number"/> 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47180137/