Skip to content

Commit

Permalink
[feat]: playwright setup added for cross browser testing (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
tarun-khanna authored Dec 28, 2023
1 parent 1566d31 commit 665a9cc
Show file tree
Hide file tree
Showing 16 changed files with 1,218 additions and 660 deletions.
5 changes: 5 additions & 0 deletions .changeset/gentle-jobs-thank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@razorpay/i18nify": minor
---

[feat]: playwright setup added for cross browser testing
25 changes: 25 additions & 0 deletions .github/workflows/playwright.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Playwright Tests
on:
pull_request:

jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 20.3.1
- name: Install dependencies
run: yarn install
- name: Install Playwright Browsers
run: npx playwright install --with-deps
- name: Run Playwright tests
run: yarn test:browser
- uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-report
path: playwright-report/
retention-days: 30
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
node_modules
lib
.DS_Store
coverage
coverage
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
2 changes: 2 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ const config = {
collectCoverage: true,
preset: 'ts-jest',
testEnvironment: 'jsdom',
testMatch: ['**/__tests__/**/*.test.[jt]s?(x)', '**/?(*.)+test.[jt]s?(x)'],
collectCoverageFrom: ['**/*.{ts,js}', '!coverage/**/*.{ts,tsx,js,jsx}'],
coveragePathIgnorePatterns: ['blackbox', '.spec.ts'],
coverageThreshold: {
'./src/': {
statements: 0,
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,19 @@
"prepare": "husky install && yarn build",
"lint-staged": "lint-staged -c .lintstagedrc.json",
"release": "node ./scripts/generateGitHubRegistryNpmrc.js && changeset publish",
"publish-npm": "node ./scripts/publishToNpm.js"
"publish-npm": "node ./scripts/publishToNpm.js",
"test:browser": "npx playwright test"
},
"devDependencies": {
"@changesets/cli": "^2.26.2",
"@playwright/test": "^1.40.1",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.5",
"@types/jest": "^29.5.7",
"@types/node": "^20.10.5",
"@typescript-eslint/eslint-plugin": "^6.9.1",
"@typescript-eslint/parser": "^6.9.1",
"cross-env": "^7.0.3",
Expand Down
74 changes: 74 additions & 0 deletions playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
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: './src',
testMatch: '**/*.spec.ts',

/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!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',
/* 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',
headless: true,
locale: 'en-IN',
},

/* 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' },
},
],
});
30 changes: 30 additions & 0 deletions src/blackbox/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Page, expect } from '@playwright/test';

/**
* Injects and executes script logic, stores the return value in single div element.
* @param page Playwright page context
* @param script logic to be executed
* @returns {Promise}
*/
export async function injectScript(page: Page, script: string) {
return await page.setContent(`
<script>
async function main() {
const amount = ${script};
document.querySelector('div').textContent = amount;
}
main()
</script>
<div data-testid="main"></div>
`);
}

/**
* Asserts expected value from the content received in div element
* @param page Playwright page context
* @param expected value to be asserted from received value
* @returns {Promise}
*/
export async function assertScriptText(page: Page, expected: string) {
return await expect(page.getByTestId('main')).toHaveText(expected);
}
102 changes: 102 additions & 0 deletions src/modules/currency/__tests__/formatNumber.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { test } from '@playwright/test';
import formatNumber from '../formatNumber';
import { assertScriptText, injectScript } from '../../../blackbox/utils';

const nbsp = String.fromCharCode(160);
const nnsp = String.fromCharCode(8239);

test.describe('formatNumber', () => {
test.beforeEach(async ({ page }) => {
await page.exposeFunction('formatNumber', formatNumber);
});

test('should format the amount with default options', async ({ page }) => {
await injectScript(
page,
`await formatNumber('1000.5', { currency: 'USD' })`,
);
await assertScriptText(page, '$1,000.50');
});

test('should format the amount with custom locale and currency display', async ({
page,
}) => {
await injectScript(
page,
`await formatNumber('1500', {
currency: 'EUR',
locale: 'fr-FR',
intlOptions: {
currencyDisplay: 'code',
},
})`,
);

await assertScriptText(page, `1${nnsp}500,00${nbsp}EUR`);
});

test('should format the amount without currency symbol', async ({ page }) => {
await injectScript(page, `await formatNumber('750.75')`);
await assertScriptText(page, '750.75');
});

test('should format the amount with narrow currency symbol', async ({
page,
}) => {
await injectScript(
page,
`await formatNumber('5000', {
currency: 'JPY',
intlOptions: {
currencyDisplay: 'narrowSymbol',
},
})`,
);
await assertScriptText(page, '¥5,000');
});

test('should format a negative amount', async ({ page }) => {
await injectScript(page, `await formatNumber('-500', { currency: 'USD' })`);
await assertScriptText(page, '-$500.00');
});

test('should format with custom minimum and maximum fraction digits', async ({
page,
}) => {
await injectScript(
page,
`await formatNumber('42.12345', {
currency: 'USD',
intlOptions: {
minimumFractionDigits: 2,
maximumFractionDigits: 3,
},
})`,
);

await assertScriptText(page, '$42.123');
});

test('should format with all default options', async ({ page }) => {
await injectScript(page, `await formatNumber(12345.6789)`);
await assertScriptText(page, '12,345.679');
});

test('should handle custom currency symbol and placement', async ({
page,
}) => {
await injectScript(
page,
`await formatNumber('1000', {
currency: 'XYZ',
intlOptions: {
style: 'currency',
currencyDisplay: 'symbol',
currencySign: 'accounting',
},
})`,
);
const expected = `XYZ${nbsp}1,000.00`;
await assertScriptText(page, expected);
});
});
85 changes: 85 additions & 0 deletions src/modules/currency/__tests__/formatNumberByParts.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { test } from '@playwright/test';
import formatNumberByParts from '../formatNumberByParts';
import { assertScriptText, injectScript } from '../../../blackbox/utils';

function generateByPartsString(options: string) {
const methodCallStr = `(await formatNumberByParts(${options}))`;
return `${methodCallStr}.currencySymbol + ${methodCallStr}.integerValue + ${methodCallStr}.separator + ${methodCallStr}.decimalValue`;
}

function generateOptionsString(
number: number,
options: { currency: string; locale?: string },
) {
return `${number}, { currency: '${options.currency}', ${
options.locale ? `locale: '${options.locale}'` : ''
} }`;
}

test.describe('formatNumberByParts', () => {
test.beforeEach(async ({ page }) => {
await page.exposeFunction('formatNumberByParts', formatNumberByParts);
});

test('should format the amount correctly for a given currency', async ({
page,
}) => {
await injectScript(
page,
generateByPartsString(
generateOptionsString(12345.67, {
currency: 'USD',
locale: 'en-US',
}),
),
);

/**
* Since comparing objects on the rendered UI is not possible,
* we render and compare each key in the parsed object in the final string .
*/
await assertScriptText(page, '$12,345.67');
});

test('should use the default locale if locale is not provided', async ({
page,
}) => {
await injectScript(
page,
generateByPartsString(
generateOptionsString(12345.67, {
currency: 'USD',
}),
),
);

await assertScriptText(page, '$12,345.67');
});

test('should handle invalid currency code', async ({ page }) => {
await injectScript(
page,
generateByPartsString(
generateOptionsString(12345.67, {
currency: 'XYZ',
}),
),
);

await assertScriptText(page, 'XYZ12,345.67');
});

test('should handle different locales', async ({ page }) => {
await injectScript(
page,
generateByPartsString(
generateOptionsString(12345.67, {
currency: 'EUR',
locale: 'fr-FR',
}),
),
);

await assertScriptText(page, '€12 345,67');
});
});
23 changes: 23 additions & 0 deletions src/modules/currency/__tests__/getCurrencyList.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { test } from '@playwright/test';
import getCurrencyList from '../getCurrencyList';
import { assertScriptText, injectScript } from '../../../blackbox/utils';

test.describe('getCurrencyList', () => {
test.beforeEach(async ({ page }) => {
await page.exposeFunction('getCurrencyList', getCurrencyList);
});

test('should print symbol correctly for a given currency', async ({
page,
}) => {
await injectScript(page, `(await getCurrencyList())['USD'].symbol`);

await assertScriptText(page, '$');
});

test('should print name correctly for a given currency', async ({ page }) => {
await injectScript(page, `(await getCurrencyList())['USD'].name`);

await assertScriptText(page, 'United States Dollar');
});
});
Loading

0 comments on commit 665a9cc

Please sign in to comment.