как интегрировать Lighthouse с testcafe?

Мне нужно передать аргумент 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});
}

И в моем тест-кафе мои тесты выглядят так

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

Я не могу получить connection экземпляра chrome, который открыл testcafe, вместо создания нового chromeRunner


person gandharv garg    schedule 25.02.2019    source источник
comment
Я не знаю простого способа интегрировать «маяк» с TestCafe, и мне нужно это изучить. Я создал проблему в репозитории TestCafe - github.com/DevExpress/testcafe/issues/3493. Отслеживайте его, чтобы получать уведомления о прогрессе.   -  person mlosev    schedule 26.02.2019


Ответы (2)


существует библиотека npm под названием testcafe-lighthouse, которая помогает проверять веб-страницы с помощью 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,
  });
});
  • Аудит с пользовательским Thresold:
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

Надеюсь, это поможет вам на пути к автоматизации.

person Abhinaba    schedule 09.06.2020

Я сделал что-то подобное, я запускаю ligthouse с google chrome на конкретном порту с помощью CLI

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

Затем я делаю функцию маяка, чтобы получить порт в качестве аргумента.

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);
    });

Надеюсь, это поможет

person Dev Singh    schedule 01.04.2019
comment
не могли бы вы подробнее рассказать о npm run testcafe -- chrome:headless:cdpPort=1234? Это специальный сценарий, который вы написали для этого? - person TallKU; 14.04.2020