我正在用AVA和jsdom写一个测试。
这有效:
const rp = require('request-promise-native')
const jsdom = require('jsdom')
const {JSDOM} = jsdom
const url = 'http://localhost:8000'
rp(url).then((body) => {
const options = {
url: url,
resources: 'usable',
runScripts: 'dangerously',
}
let dom = new JSDOM(body, options)
dom.window.document.addEventListener('DOMContentLoaded', () => {
setImmediate(() => {
console.log(dom.serialize()) // works, prints <html><head></head><body><h1>Hello world!</h1></body></html>
})
})
})
外部脚本将h1添加到文档正文中。
// external.js
document.addEventListener('DOMContentLoaded', () => {
document.write('<h1>Hello world!</h1>')
})
这是http://localhost:8000的标记:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSDOM test</title>
<script src="external.js"></script>
</head>
<body>
</body>
</html>
当我在测试中尝试相同的事情时:
const rp = require('request-promise-native')
const test = require('ava')
const jsdom = require('jsdom')
const {JSDOM} = jsdom
const url = 'http://localhost:8000'
test('Check custom CSS', t => {
return rp(url).then((body) => {
const options = {
url: url,
resources: 'usable',
runScripts: 'dangerously',
}
let dom = new JSDOM(body, options)
dom.window.document.addEventListener('DOMContentLoaded', () => {
setImmediate(() => {
console.log(dom.serialize()) // nothing gets printed
})
})
t.pass('passed')
})
})
console.log
未被调用。我希望<html><head></head><body><h1>Hello world!</h1></body></html>
能够打印出来,而不是没有输出。
总之,我想:
这样做的最佳方式是什么?
以下是最低工作示例:https://github.com/cg433n/jsdom-test