【发布时间】:2020-10-06 23:08:56
【问题描述】:
我正在使用Puppeteer 在 react 环境中测试客户端功能 - 该功能本身不使用 React,但旨在导入 es6 react 模块并在最终用户 DOM 环境中运行。我需要 Puppeteer,因为这个函数依赖于诸如 innerText 之类的属性,这些属性在 jsdom 中不可用。
这个函数接受一个 DOM 元素作为参数,但是我在为它编写测试文件时遇到了麻烦。这是我的代码示例:
import path from 'path';
import puppeteer from 'puppeteer';
import {getSelectionRange, setSelectionRange} from './selection';
describe(
'getSelection should match setSelection',
() => {
let browser;
let page;
beforeAll(async done => {
try {
browser = await puppeteer.launch();
page = await browser.newPage();
await page.goto(
`file://${path.join(process.env.ROOT,
'testFiles/selection_range_test.html')}`
);
await page.exposeFunction(
'setSelectionRange',
(el, start, end) => setSelectionRange(el, start, end)
);
await page.exposeFunction(
'getSelectionRange',
el => getSelectionRange(el)
);
} catch(error) {
console.error(error);
}
done();
});
afterAll(async done => {
await browser.close();
done();
});
it('should match on a node with only one text node children', async () => {
const {selection, element, argEl} = await page.evaluate(async () => {
const stn = document.getElementById('single-text-node');
// Since console.log will output in the Puppeteer browser and not in node console,
// I added a line inside the selectionRange function to return the element it receives
// as an argument.
const argEl = await window.setSelectionRange(stn, 1, 10);
const selectionRange = await window.getSelectionRange(stn);
return {selection: selectionRange, element: stn, argEl};
});
// Outputs <div id="single-text-node">...</div>
// (the content is long so I skipped it, but it displays the correct value here)
console.log(element.outerHTML);
// Outputs {}
console.log(argEl);
});
}
);
如cmets中所述,直接从page.evaluate()返回的元素是正确的,但是当作为参数传递时,函数接收到一个空对象。我怀疑是范围问题,但我完全没有解决方案。
【问题讨论】:
-
如果你
console.log(argEl)inside 你的evaluate块会发生什么?它打印什么? -
首先,您不能信任控制台输出。它输出对象自己的可枚举属性。如果你想调试一个值,那就用真正的调试器调试它。
-
如果我理解正确的话,无论是暴露的函数还是 page.evaluste() 都不能在浏览器和 Node.js 上下文之间传输不可序列化的值(包括 DOM 元素)。
-
一旦你知道了确切的命令,它实际上真的很简单。见stackoverflow.com/questions/63671251/…
-
它应该打印一些东西,但在 chrome devtool 中而不是在您的终端中。
标签: javascript reactjs testing jestjs puppeteer