Skip to content

Commit

Permalink
Example for Playwright Coverage Reports
Browse files Browse the repository at this point in the history
  • Loading branch information
cenfun committed Mar 24, 2024
1 parent e892f93 commit 51e5d3e
Show file tree
Hide file tree
Showing 12 changed files with 327 additions and 1 deletion.
31 changes: 31 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// https://eslint.org/docs/rules/
module.exports = {
'root': true,
// system globals
'env': {
'node': true,
'browser': true,
'amd': true,
'commonjs': true,
'es6': true
},
// other globals
'globals': {
},

'plugins': [
],

'extends': [
'plus'
],

'parserOptions': {
'ecmaVersion': 'latest',
'sourceType': 'module'
},

'rules': {
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'warn'
}
};
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

/coverage-reports
/package-lock.json
18 changes: 18 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"editor.formatOnSave": true,
"eslint.format.enable": true,
"eslint.validate": [
"typescript",
"javascript"
],
"git.ignoreLimitWarning": true
}
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,19 @@
# playwright-coverage
Playwright Coverage Reports
Example for Playwright Coverage Reports

## Install
```sh
npm i monocart-coverage-reports -D
```

- Create `autoTestFixture` for collecting coverage data, see [fixtures.ts](fixtures.ts)
- Create [global.setup.ts](global.setup.ts) and [global-teardown.ts](global-teardown.ts) for generating coverage reports
- Set coverage options in config [mcr.config.ts](mcr.config.ts)
- Playwright config [playwright.config.ts](playwright.config.ts)

```sh
npm run test
```
The coverage report will be found here: `coverage-reports/index.html`

Check repo [monocart coverage reports](https://github.com/cenfun/monocart-coverage-reports) for more options.
44 changes: 44 additions & 0 deletions fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { test as testBase } from '@playwright/test';
import MCR from 'monocart-coverage-reports';
import coverageOptions from './mcr.config';

// fixtures
const test = testBase.extend({
autoTestFixture: [async ({ page }, use) => {

const isChromium = test.info().project.name === 'chromium';

// console.log('autoTestFixture setup...');
// coverage API is chromium only
if (isChromium) {
await Promise.all([
page.coverage.startJSCoverage({
resetOnNavigation: false
}),
page.coverage.startCSSCoverage({
resetOnNavigation: false
})
]);
}

await use('autoTestFixture');

// console.log('autoTestFixture teardown...');
if (isChromium) {
const [jsCoverage, cssCoverage] = await Promise.all([
page.coverage.stopJSCoverage(),
page.coverage.stopCSSCoverage()
]);
const coverageList = [... jsCoverage, ... cssCoverage];
// console.log(coverageList.map((item) => item.url));
const mcr = MCR(coverageOptions);
await mcr.add(coverageList);
}

}, {
scope: 'test',
auto: true
}]
});

export { test };
9 changes: 9 additions & 0 deletions global-teardown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import MCR from 'monocart-coverage-reports';
import coverageOptions from './mcr.config';

async function globalTeardown(config) {
const mcr = MCR(coverageOptions);
await mcr.generate();
}

export default globalTeardown;
9 changes: 9 additions & 0 deletions global.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import MCR from 'monocart-coverage-reports';
import coverageOptions from './mcr.config';

async function globalSetup(config) {
const mcr = MCR(coverageOptions);
await mcr.cleanCache();
}

export default globalSetup;
16 changes: 16 additions & 0 deletions mcr.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export default {

name: 'My Playwright Coverage Report',

reports: [
'console-details',
'v8'
],

// entryFilter: {
// '**/node_modules/**': false,
// '**/*.js': true
// },

outputDir: './coverage-reports'
};
18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "playwright-coverage",
"version": "1.0.0",
"description": "Playwright Coverage Reports",
"main": "index.js",
"scripts": {
"test": "npx playwright test"
},
"license": "MIT",
"devDependencies": {
"@playwright/test": "^1.42.1",
"@types/node": "^20.11.30",
"eslint": "^8.57.0",
"eslint-config-plus": "^1.0.6",
"monocart-coverage-reports": "^2.7.6"
},
"dependencies": {}
}
93 changes: 93 additions & 0 deletions playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { defineConfig, devices } from '@playwright/test';

/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();

/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests',

/* Run tests in files in parallel */
fullyParallel: true,

/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: Boolean(process.env.CI),

/* Retry on CI only */
retries: process.env.CI ? 2 : 0,

/* Opt out of parallel tests on CI. */
// workers: process.env.CI ? 1 : undefined,

/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',

globalSetup: 'global.setup.ts',
globalTeardown: 'global-teardown.ts',

/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {

/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://127.0.0.1:3000',

/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry'
},

/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
... devices['Desktop Chrome']
}
},

{
name: 'firefox',
use: {
... devices['Desktop Firefox']
}
},

{
name: 'webkit',
use: {
... devices['Desktop Safari']
}
}

/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },

/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
]

/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://127.0.0.1:3000',
// reuseExistingServer: !process.env.CI,
// },
});
54 changes: 54 additions & 0 deletions tests/demo-todo-app.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { expect } from '@playwright/test';
import { test } from '../fixtures';

test.beforeEach(async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc');
});

const TODO_ITEMS = [
'buy some cheese',
'feed the cat',
'book a doctors appointment'
];

test.describe('New Todo', () => {
test('should allow me to add todo items', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');

// Create 1st todo.
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');

// Make sure the list only has one todo item.
await expect(page.getByTestId('todo-title')).toHaveText([
TODO_ITEMS[0]
]);

// Create 2nd todo.
await newTodo.fill(TODO_ITEMS[1]);
await newTodo.press('Enter');

// Make sure the list now has two todo items.
await expect(page.getByTestId('todo-title')).toHaveText([
TODO_ITEMS[0],
TODO_ITEMS[1]
]);


});

test('should clear text input field when an item is added', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');

// Create one todo item.
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');

// Check that input is empty.
await expect(newTodo).toBeEmpty();

});

});
9 changes: 9 additions & 0 deletions tests/example.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { expect } from '@playwright/test';
import { test } from '../fixtures';

test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');

// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});

0 comments on commit 51e5d3e

Please sign in to comment.