When I create a testing framework, I think of the best solution for the test results, so I didn’t have a boilerplate to reuse the same code and NPM packages so I choose the best npm for each project. I’ve worked with frameworks such as Selenium, Testcafe, NightwatchJS, WebdriverIO, Cypress, and Playwright.
And these 3 NPM package are useful for all the frameworks and projects.
1) Data Generation with FakerJS
@faker-js/faker: It’s an open-source library that returns random data for different categories, like person, commerce, company, and texts, and it can be localized to different languages.
Testing with random data can generate info for different lengths and languages that sometimes you can see that some text is overlapped or produce errors if the input is not validated correctly for example with some special characters.
I prefer tests with more realistic data than names like Name123423, and I don’t like to use hard-coded values.
Install
npm install --save-dev @faker-js/faker
Example
Add the import and check the Faker API for all available data. For example, I am using the following faker data to generate a random server info.
import { faker } from '@faker-js/faker';
test('Should add a server', async ({ page }) => {
const addServerPage = new AddServerPage(page);
await addServerPage.goTo();
//The key is a int number between 1 and 999_999
const key = faker.number.int({ min: 1, max: 999_999 });
const name = faker.company.name();
const url = faker.internet.url();
await addServerPage.key.fill(key.toString());
await addServerPage.name.fill(name);
await addServerPage.url.fill(url);
id = await addServerPage.saveClick();
const serversPage = new ServersPage(page);
//Assert that the random data is the same
await serversPage.checkRow(key, name, url);
}
You can also use Faker in Postman, which can be helpful for performance testing and generating different values.
2) Analyze your webpage with Lighthouse
Lighthouse is a tool developed by Google that analyzes your web page in different aspects:
Performance
Accessibility
Best Practices
SEO
You can install the playwright-lighthouse plugin to get the scores in your playwright test.
Install
npm install --save-dev playwright-lighthouse playwright lighthouse
Example
You can set the percentage of each area that fails the test if it is under the expected percentage threshold.
import { playAudit } from 'playwright-lighthouse';
import playwright from 'playwright';
test('Should check lighthouse audit', async () => {
const browser = await playwright['chromium'].launch({
args: ['--remote-debugging-port=9222'],
});
//With manual context or page is needed to setup the video
page = await browser.newPage();
await page.goto('https://www.google.com');
const lighthouseReport = await playAudit({
page: page,
port: 9222,
thresholds: {
performance: 60,
accessibility: 90,
'best-practices': 80,
seo: 80,
pwa: 80,
}
});
//If you want to check the score and maybe include in some test you can access with this code
const accessibilityScore = lighthouseReport.lhr.categories.accessibility.score! * 100;
console.log(accessibilityScore);
});
If the score is less than your threshold, you will have an error similar to this:
Error: playwright lighthouse - A threshold is not matching the expectation.
accessibility record is 81 and is under the 90 threshold
at tests/Accessibility/pageAccessibility.spec.ts:27:34
3) Format your code and fix missing awaits ESLint
You can find and fix some common problems in JavaScript/TypeScript with ESLint. It checks your code for “lint” (mistakes, bad practices, or coding style issues) before you run it.
One helpful rule is to ensure you don’t forget to include the await keyword.
And you can define your coding style format, for example, use 4 spaces for tabs, or use single quotes instead of double quotes, and when you save the changes, auto-fix all the lint rules.
Install
Install the following ESLint packages
npm install --save-dev eslint typescript-eslint typescript
npm install -D eslint-plugin-playwright
Install the ESLint VS Code Extension.
To get the ESLint errors highlighted in your VS Code, install the ESLint extension.
If you want to be installed when the project is opened in VS Code, you can create an extensions.json folder inside the .vscode folder.
{
"recommendations": [
"ms-playwright.playwright",
"dbaeumer.vscode-eslint"
]
}
Create a settings.json file.
To auto-fix the errors when you save your file, create a .vscode folder, add a settings.json file, and add the following setting option:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
}
With this option, check all the rules and fix the format each time you save your file.
Create a tsconfig.json file that checks some syntax for TypeScript files..
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "node",
"strict": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"types": ["node", "eslint"]
}
}
Create an eslint.config.mjs file that contains all the rules and formatting code for your project.
import playwright from 'eslint-plugin-playwright';
import tseslint from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
// Import recommended config objects for flat config
const tsRecommended = tseslint.configs.recommended;
const playwrightRecommended = playwright.configs['flat/recommended'];
export default [
{
...playwrightRecommended,
//Ignores some config files and custom reporters
ignores: [
'checkly.config.ts',
'eslint.config.mjs',
'report/',
'steps-reports/',
'test-results/',
'blob-report/'
],
files: ['**/*.ts'],
languageOptions: {
parser: tsParser,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
},
// Explicitly declare both plugins for the rules below
plugins: {
'@typescript-eslint': tseslint,
'playwright': playwright
},
rules: {
...playwrightRecommended.rules,
...tsRecommended.rules,
//Code formats
indent: ['error', 4, { SwitchCase: 1 }],
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'always'],
},
}
];
If you want to exclude some rule you can add a comment at the beginning of the file to ignore the rule
/* eslint-disable playwright/expect-expect */
import { test } from '@playwright/test';
import { DashboardPage } from '../../pages/Effiziente/dashboardPage';
import { AnnotationType } from '../../utils/annotations/AnnotationType';
import * as allure from 'allure-js-commons';
To check the syntax and fix some error use this command
npm run lint --fix
My playwright sample includes all the code and examples and is configured with these and some additional NPM packages
Thank you for reading, and feel free to suggest a topic for a new article and share if you think it is useful. Enjoy testing!!