如何将灯塔与testcafe集成在一起?

时间:2019-02-25 10:09:43

标签: google-chrome audit testcafe lighthouse

我需要在调用connection时传递lighthouse参数

https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/index.js#L41

async function lighthouse(url, flags = {}, configJSON, connection) {
  // verify the url is valid and that protocol is allowed
  if (url && (!URL.isValid(url) || !URL.isProtocolAllowed(url))) {
    throw new LHError(LHError.errors.INVALID_URL);
  }

  // set logging preferences, assume quiet
  flags.logLevel = flags.logLevel || 'error';
  log.setLevel(flags.logLevel);

  const config = generateConfig(configJSON, flags);

  connection = connection || new ChromeProtocol(flags.port, flags.hostname);

  // kick off a lighthouse run
  return Runner.run(connection, {url, config});
}

在我的testcafe中,我的测试看起来像

test('Run lighthouse, async t => {
  lighthouse('https://www.youtube.com', {}, {}, ????)
})

我无法获取testcafe打开的chrome实例的connection,而不是生成新的chromeRunner

2 个答案:

答案 0 :(得分:2)

有一个名为testcafe-lighthouse的npm库,该库有助于使用TestCafe审核网页。它还具有生成HTML详细报告的功能。

通过以下方式安装插件:

$ yarn add -D testcafe-lighthouse
# or 
$ npm install --save-dev testcafe-lighthouse
  • 具有默认阈值的审核
import { testcafeLighthouseAudit } from 'testcafe-lighthouse';

fixture(`Audit Test`).page('http://localhost:3000/login');

test('user performs lighthouse audit', async () => {
  const currentURL = await t.eval(() => document.documentURI);
  await testcafeLighthouseAudit({
    url: currentURL,
    cdpPort: 9222,
  });
});
  • 使用自定义阈值进行审核:
import { testcafeLighthouseAudit } from 'testcafe-lighthouse';

fixture(`Audit Test`).page('http://localhost:3000/login');

test('user page performance with specific thresholds', async () => {

  const currentURL = await t.eval(() => document.documentURI);

  await testcafeLighthouseAudit({
    url: currentURL,
    thresholds: {
      performance: 50,
      accessibility: 50,
      'best-practices': 50,
      seo: 50,
      pwa: 50,
    },
    cdpPort: 9222,
  });
});
  • 您需要像下面这样开始测试:
# headless mode, preferable for CI
npx testcafe chrome:headless:cdpPort=9222 test.js

# non headless mode
npx testcafe chrome:emulation:cdpPort=9222   test.js

我希望它能帮助您实现自动化。

答案 1 :(得分:1)

我做了类似的事情,我使用CLI在特定端口上使用Google chrome启动了ligthouse

npm run testcafe -- chrome:headless:cdpPort=1234

然后我使用lighthouse函数来获取port作为参数

export default async function lighthouseAudit(url, browser_port){
    let result = await lighthouse(url, {
        port: browser_port,     // Google Chrome port Number
        output: 'json',
        logLevel: 'info',
    });
    return result;
};

然后,您可以像

一样简单地运行审核
    test(`Generate Light House Result `, async t => {
        auditResult = await lighthouseAudit('https://www.youtube.com',1234);
    });

希望有帮助