寻找一种编写自定义Puppeteer命令的方法

时间:2018-04-04 04:07:04

标签: javascript testing integration-testing nightwatch.js puppeteer

以前使用Nightwatch.js我能够创建自定义的Nightwatch命令:https://github.com/nightwatchjs/nightwatch-docs/blob/master/guide/extending-nightwatch/custom-commands.md

我想知道Puppeteer是否存在这样的事情 - 我最近看到的是:Is there a way to add script to add new functions in evaluate() context of chrome+puppeeter?

但它仍然远离我想要的东西。我希望能够拨打page.commonAction(...)而不是

page.x();
page.y();
page.z();

1 个答案:

答案 0 :(得分:0)

您始终可以使用可以调用的函数创建自己的脚本。例如,我在同一个文件夹中有一个myFunctions.js,我从中命名

const mf = require('./myFunctions.js');

在myFunctions.js中我有例如这个函数:

async function verifyElementPresent(page, selector) {
  let verifySelector = await page.$(selector);
  if (verifySelector !== null) {
    console.log(found('> OK - Element present'));
  } else {
    console.log(notfound('>>> ERROR - Element not present: ' + selector));
  }
}

所以现在,在我的Puppeteer脚本中我所要做的就是写:

mf.verifyElementPresent(page, '#headerTitle');

它会在控制台中打印结果。

希望这有帮助。