木偶console.log-如何查看JSHandle @ object的内部?

时间:2018-08-03 15:47:12

标签: javascript reactjs testing redux puppeteer

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

JSHandle@object

但是,当redux-logger将对象记录到控制台(prevState,nextState)时,Puppeeter会在控制台输出中显示bazel build --cxxopt='--std=c++11' -c opt --fat_apk_cpu=x86,x86_64,arm64-v8a,armeabi-v7a tensorflow/contrib/lite/java:tensorflow-lite 。如何查看该对象内部的键和属性?

2 个答案:

答案 0 :(得分:3)

您可以通过 argsJSHandle 获得 await

对我来说最好的方法是描述来自浏览器的错误并捕获所需类型的 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)

答案 1 :(得分:1)

如果将consoleMessage.args()直接放置在console.log()内而不将其括在template literals中,则可以打印表示传递给{的每个参数的JSHandles的键和值{3}}在页面上下文中:

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],
        ...