如何使用 jsdom 在 input[text] 元素上创建 `oninput` 事件?
How to create `oninput` event on input[text] element with jsdom?
这是我的 jsdom 设置。我想测试 input[text]
元素的 oninput 事件。如何触发oninput
事件?因为只是设置element.value
不会触发这个事件。
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
suiteSetup(() => {
return JSDOM.fromFile("./views/index.html", {
runScripts: "dangerously",
resources: "usable"
}).then(dom => {
global.dom = dom
global.window = dom.window;
global.document = dom.window.document;
});
});
根据,您可以创建一个事件对象,并使用它通过执行JS来触发input
事件。
由于您使用的是 JSDOM,因此您可以通过 eval
在页面上下文中执行此操作。
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const dom = new JSDOM(
`<!DOCTYPE html>
<meta charset="utf-8">
<title>Test</title>
<input>
<p>Hello world</p>
<script>
document.querySelector("input").addEventListener("input", event =>
document.querySelector("p").textContent = event.target.value
);
</script>`,
{
runScripts: 'dangerously',
resources: 'usable',
}
);
dom.window.eval(`
const input = document.querySelector("input");
input.value = "New value";
const event = new Event('input', {
bubbles: true,
cancelable: true
});
input.dispatchEvent(event);
`);
console.log(dom.serialize());
我无法改进之前的答案,因为我收到错误:edit queue is full
。
由于 jsDOM
为您提供了一个接近完整的浏览器环境,因此您不需要 eval
。您可以直接从 Node 触发事件。
const input = dom.window.document.querySelector("input");
input.value = "New value";
const event = new Event('input', {
bubbles: true,
cancelable: true
});
input.dispatchEvent(event);
这是我的 jsdom 设置。我想测试 input[text]
元素的 oninput 事件。如何触发oninput
事件?因为只是设置element.value
不会触发这个事件。
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
suiteSetup(() => {
return JSDOM.fromFile("./views/index.html", {
runScripts: "dangerously",
resources: "usable"
}).then(dom => {
global.dom = dom
global.window = dom.window;
global.document = dom.window.document;
});
});
根据input
事件。
由于您使用的是 JSDOM,因此您可以通过 eval
在页面上下文中执行此操作。
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const dom = new JSDOM(
`<!DOCTYPE html>
<meta charset="utf-8">
<title>Test</title>
<input>
<p>Hello world</p>
<script>
document.querySelector("input").addEventListener("input", event =>
document.querySelector("p").textContent = event.target.value
);
</script>`,
{
runScripts: 'dangerously',
resources: 'usable',
}
);
dom.window.eval(`
const input = document.querySelector("input");
input.value = "New value";
const event = new Event('input', {
bubbles: true,
cancelable: true
});
input.dispatchEvent(event);
`);
console.log(dom.serialize());
我无法改进之前的答案,因为我收到错误:edit queue is full
。
由于 jsDOM
为您提供了一个接近完整的浏览器环境,因此您不需要 eval
。您可以直接从 Node 触发事件。
const input = dom.window.document.querySelector("input");
input.value = "New value";
const event = new Event('input', {
bubbles: true,
cancelable: true
});
input.dispatchEvent(event);