我正在尝试通过模拟按下“escape”键来关闭一个模态对话框
为了背景,这是我正在编写的一个自动化测试,但我正在寻找纯粹的JS解决方案。我在Windows 10上使用Firefox浏览器。
更新:我刚刚了解到TestCafe的最新版本(v3)默认使用本机事件,但只适用于某些浏览器。Firefox不是其中之一。通过将我的测试切换到Google Chrome,我现在可以自动化模拟用户按下Esc键。
我只是出于信息目的说这个;我仍然希望得到对我原始问题的答案。希望这能为将来的某人节省很多时间。
<dialog>
元素。我将在下面解释这个例子:
document.addEventListener("keydown", (e) => {
console.log(e)
});
document.addEventListener("keyup", (e) => {
console.log(e)
});
document.addEventListener("keypress", (e) => {
console.log(e)
});
const dialog = document.querySelector(`dialog`);
const openDialogButton = document.querySelector(`#open-dialog-button`);
openDialogButton.addEventListener("click", () => {
dialog.showModal();
});
const syntheticEscapeButton = document.querySelector(`#synthetic-escape-button`);
syntheticEscapeButton.addEventListener("click", () => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
altKey: false,
code: "Escape",
ctrlKey: false,
isComposing: false,
key: "Escape",
location: 0,
metaKey: false,
repeat: false,
shiftKey: false,
which: 27,
charCode: 0,
keyCode: 27,
}));
document.dispatchEvent(
new KeyboardEvent("keyup", {
altKey: false,
code: "Escape",
ctrlKey: false,
isComposing: false,
key: "Escape",
location: 0,
metaKey: false,
repeat: false,
shiftKey: false,
which: 27,
charCode: 0,
keyCode: 27,
}));
});
const closeDialogButton = document.querySelector(`#close-dialog-button`);
closeDialogButton.addEventListener("click", () => {
dialog.close();
});
<input id="input-1" type="text">
<button id="open-dialog-button">Open Dialog</button>
<dialog>
<div id="dialog-body">
<p>Press the escape key to close the dialog box.</p>
<input id="input-2" type="text">
<button id="synthetic-escape-button">Press Synthetic Escape</button>
<button id="close-dialog-button">Close Dialog</button>
</div>
</dialog>
- 如果您点击“打开对话框”按钮,然后按下 escape 键,对话框将会关闭。
- 如果您点击“打开对话框”按钮,然后点击“按下合成的Escape”按钮,对话框不会关闭。
无论哪种方式,键盘事件监听器都会触发。为什么在情况 #1 中 <dialog>
关闭了,而在情况 #2 中却没有关闭?我该如何让合成的 escape 键关闭 <dialog>
,就像情况 #1 一样?
为了背景,这是我正在编写的一个自动化测试,但我正在寻找纯粹的JS解决方案。我在Windows 10上使用Firefox浏览器。
更新:我刚刚了解到TestCafe的最新版本(v3)默认使用本机事件,但只适用于某些浏览器。Firefox不是其中之一。通过将我的测试切换到Google Chrome,我现在可以自动化模拟用户按下Esc键。
我只是出于信息目的说这个;我仍然希望得到对我原始问题的答案。希望这能为将来的某人节省很多时间。
cy.type('{esc}')
或者使用类似于https://github.com/dmtrKovalenko/cypress-real-events的库。 - undefined