How to use installCoverageHooks method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

coverage.js

Source: coverage.js Github

copy
1/**
2 * Copyright 2017 Google Inc. All rights reserved.
3 * Modifications copyright (c) Microsoft Corporation.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18const path = require('path');
19const fs = require('fs');
20
21/**
22 * @param {Map<string, boolean>} apiCoverage
23 * @param {Object} events
24 * @param {string} className
25 * @param {!Object} classType
26 */
27function traceAPICoverage(apiCoverage, api, events) {
28  const uninstalls = [];
29  for (const [name, classType] of Object.entries(api)) {
30    const className = name.substring(0, 1).toLowerCase() + name.substring(1);
31    for (const methodName of Reflect.ownKeys(classType.prototype)) {
32      const method = Reflect.get(classType.prototype, methodName);
33      if (methodName === 'constructor' || typeof methodName !== 'string' || methodName.startsWith('_') || typeof method !== 'function')
34        continue;
35
36      apiCoverage.set(`${className}.${methodName}`, false);
37      const override = function(...args) {
38        apiCoverage.set(`${className}.${methodName}`, true);
39        return method.call(this, ...args);
40      };
41      Object.defineProperty(override, 'name', { writable: false, value: methodName });
42      Reflect.set(classType.prototype, methodName, override);
43      uninstalls.push(() => Reflect.set(classType.prototype, methodName, method));
44    }
45    if (events[name]) {
46      for (const event of Object.values(events[name])) {
47        if (typeof event !== 'symbol')
48          apiCoverage.set(`${className}.emit(${JSON.stringify(event)})`, false);
49      }
50      const method = Reflect.get(classType.prototype, 'emit');
51      Reflect.set(classType.prototype, 'emit', function(event, ...args) {
52        if (typeof event !== 'symbol' && this.listenerCount(event))
53          apiCoverage.set(`${className}.emit(${JSON.stringify(event)})`, true);
54        return method.call(this, event, ...args);
55      });
56      uninstalls.push(() => Reflect.set(classType.prototype, 'emit', method));
57    }
58  }
59  return () => uninstalls.forEach(u => u());
60}
61
62/**
63 * @param {string} browserName
64 */
65function apiForBrowser(browserName) {
66  const events = require('../../lib/client/events').Events;
67  const api = require('../../lib/client/api');
68  const otherBrowsers = ['chromium', 'webkit', 'firefox'].filter(name => name.toLowerCase() !== browserName.toLowerCase());
69  const filteredKeys = Object.keys(api).filter(apiName => {
70    if (apiName.toLowerCase().startsWith('android'))
71      return browserName === 'android';
72    if (apiName.toLowerCase().startsWith('electron'))
73      return browserName === 'electron';
74    return browserName !== 'electron' && browserName !== 'android' &&
75        !otherBrowsers.some(otherName => apiName.toLowerCase().startsWith(otherName));
76  });
77  const filteredAPI = {};
78  for (const key of filteredKeys)
79    filteredAPI[key] = api[key];
80  return {
81    api: filteredAPI,
82    events
83  }
84}
85
86/**
87 * @param {string} browserName
88 */
89function installCoverageHooks(browserName) {
90  const {api, events} = apiForBrowser(browserName);
91  const coverage = new Map();
92  const uninstall = traceAPICoverage(coverage, api, events);
93  return {coverage, uninstall};
94}
95
96class CoverageEnv {
97  /**
98   * @param {string} browserName
99   */
100  constructor(browserName) {
101    this.browserName = browserName;
102  }
103
104  /**
105   * @param {import('folio').WorkerInfo} workerInfo
106   */
107  async beforeAll(workerInfo) {
108    this.coverage = installCoverageHooks(this.browserName);
109  }
110
111  /**
112   * @param {import('folio').WorkerInfo} workerInfo
113   */
114   async afterAll(workerInfo) {
115    const { coverage, uninstall } = this.coverage;
116    uninstall();
117    const coveragePath = path.join(__dirname, '..', 'coverage-report', workerInfo.workerIndex + '.json');
118    const coverageJSON = Array.from(coverage.keys()).filter(key => coverage.get(key));
119    await fs.promises.mkdir(path.dirname(coveragePath), { recursive: true });
120    await fs.promises.writeFile(coveragePath, JSON.stringify(coverageJSON, undefined, 2), 'utf8');
121  }
122}
123
124module.exports = {
125  installCoverageHooks,
126  CoverageEnv
127};
128
Full Screen

checkCoverage.js

Source: checkCoverage.js Github

copy
1/**
2 * Copyright Microsoft Corporation. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16const path = require('path');
17const fs = require('fs');
18const {installCoverageHooks} = require('./coverage');
19
20const browserName = process.argv[2] || 'chromium';
21
22let api = new Set(installCoverageHooks(browserName).coverage.keys());
23
24// coverage exceptions
25
26if (browserName === 'chromium') {
27  // Sometimes we already have a background page while launching, before adding a listener.
28  api.delete('browserContext.emit("backgroundpage")');
29}
30
31if (browserName !== 'chromium') {
32  // we don't have CDPSession in non-chromium browsers
33  api.delete('browser.newBrowserCDPSession');
34  api.delete('browser.startTracing');
35  api.delete('browser.stopTracing');
36  api.delete('browserContext.backgroundPages');
37  api.delete('browserContext.serviceWorkers');
38  api.delete('browserContext.newCDPSession');
39  api.delete('browserContext.emit("backgroundpage")');
40  api.delete('browserContext.emit("serviceworker")');
41  api.delete('cDPSession.send');
42  api.delete('cDPSession.detach');
43  api.delete('coverage.startJSCoverage');
44  api.delete('coverage.stopJSCoverage');
45  api.delete('coverage.startCSSCoverage');
46  api.delete('coverage.stopCSSCoverage');
47  api.delete('page.pdf');
48}
49
50// Some permissions tests are disabled in webkit. See permissions.jest.js
51if (browserName === 'webkit')
52  api.delete('browserContext.clearPermissions');
53
54const coverageDir = path.join(__dirname, '..', 'coverage-report');
55
56const coveredMethods = new Set();
57for (const file of getCoverageFiles(coverageDir)) {
58  for (const method of JSON.parse(fs.readFileSync(file, 'utf8')))
59    coveredMethods.add(method);
60}
61
62
63let success = true;
64for (const method of api) {
65  if (coveredMethods.has(method))
66    continue;
67  success = false;
68  console.log(`ERROR: Missing coverage for "${method}"`)
69}
70
71process.exit(success ? 0 : 1);
72
73function * getCoverageFiles(dir) {
74  for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
75    if (entry.isDirectory())
76      yield * getCoverageFiles(path.join(dir, entry.name))
77    else
78      yield path.join(dir, entry.name);
79  }
80}
81
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)