Puppeteer console.log - 如何查看 JSHandle@object 内部?

IT技术 javascript reactjs testing redux puppeteer
2021-03-27 20:59:43

我有一个 React/Redux 应用程序,我正在使用 Puppeteer 进行测试。根据文档,我使用以下代码来显示控制台输出:

page.on('console', msg => {
    for(let i = 0; i < msg.args().length; ++i) {
        let text = msg.args()[i];
        console.log(`${i}: ${text}`);
    }
});

但是,当 redux-logger 将对象记录到控制台(prevState、nextState)时,Puppeeter 会改为显示JSHandle@object在我的控制台输出中。如何查看此对象中的键和属性?

2个回答

如果将consoleMessage.args()直接放在里面console.log()而不将它们包含在模板文字中,则可以打印代表传递给页面上下文的每个参数JSHandle的键和值console.log()

page.on('console', msg => {
  for (let i = 0; i < msg.args().length; i++) {
    console.log(msg.args()[i]);
  }
});

结果的开头将如下所示:

JSHandle {
  _context:
   ExecutionContext {
     _client:
      CDPSession {
        domain: null,
        _events: [Object],
        ...

你可以argsJSHandleawait它。

对我来说最好的方法是描述来自浏览器的错误并捕获所需类型的console通知:

import { ConsoleMessage, Page, JSHandle } from 'puppeteer';
const chalk = require('chalk');

export const listenPageErrors = async (page: Page) => {
  // make args accessible
  const describe = (jsHandle) => {
    return jsHandle.executionContext().evaluate((obj) => {
      // serialize |obj| however you want
      return `OBJ: ${typeof obj}, ${obj}`;
    }, jsHandle);
  }

  const colors: any = {
    LOG: chalk.grey, // (text: any) => text,
    ERR: chalk.red,
    WAR: chalk.yellow,
    INF: chalk.cyan,
  };

  // listen to browser console there
  page.on('console', async (message: ConsoleMessage) => {
    const args = await Promise.all(message.args().map(arg => describe(arg)));
    // make ability to paint different console[types]
    const type = message.type().substr(0, 3).toUpperCase();
    const color = colors[type] || chalk.blue;
    let text = '';
    for (let i = 0; i < args.length; ++i) {
      text += `[${i}] ${args[i]} `;
    }
    console.log(color(`CONSOLE.${type}: ${message.text()}\n${text} `));
  });
}

把它放在const page = await browser.newPage();之间page.goto(URL),它会正常工作

const page = await browser.newPage();
await listenPageErrors(page); // <- like there
page.goto(URL)

Promise.all(msg.args()部分还是错的,我已经为你修复了。谢谢!
2021-05-30 20:59:43
关于jsHandle as JSHandle - Unexpected token, expected ","可能删除as JSHandle类型描述,这可能是由您的 Tslint/eslint 选项引起的
2021-05-31 20:59:43
大声笑,你是在 2 小时前写的,我已经找到了!你好!对我来说,它打破了jsHandle as JSHandle-Unexpected token, expected ","
2021-06-01 20:59:43
嘿,伊戈尔!:) 我在这里遇到了另一个木偶问题,以为你可能知道解决方案,但在 Telegram 中找不到你问。是否可以知道当前是否正在加载 puppeteer 页面?“刷新按钮”当前状态的模拟,可能是?
2021-06-11 20:59:43
然后message这里是未定义的:const type = message.type().
2021-06-21 20:59:43