Skip to content

test: optimize tests by adding shared utility functions #1063

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
25 changes: 7 additions & 18 deletions tests/missingRides.spec.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,21 @@
import { test, expect } from '@playwright/test'
import moment from 'moment'
import { test } from '@playwright/test'
import { expect } from './utils'

test('verify API call to gtfs_agencies/list - "missing rides"', async ({ page }) => {
let apiCallMade = false
page.on('request', (request) => {
if (request.url().includes('gtfs_agencies/list')) {
apiCallMade = true
}
})
const callAssertion = expect(page).toCall('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'נסיעות שלא בוצעו', exact: true }).click()
await page.getByLabel('חברה מפעילה').click()
expect(apiCallMade).toBeTruthy()

await callAssertion
})

test('Verify date_from parameter from "missing rides"', async ({ page }) => {
const apiRequest = page.waitForRequest((request) => request.url().includes('gtfs_agencies/list'))
const dateAssertion = expect(page).toHaveRecentDateFrom('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'נסיעות שלא בוצעו', exact: true }).click()

const request = await apiRequest
const url = new URL(request.url())
const dateFromParam = url.searchParams.get('date_from')
const dateFrom = moment(dateFromParam)
const daysAgo = moment().diff(dateFrom, 'days')

expect(daysAgo).toBeGreaterThanOrEqual(0)
expect(daysAgo).toBeLessThanOrEqual(3)
await dateAssertion
})
33 changes: 11 additions & 22 deletions tests/patterns.spec.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,21 @@
import { test, expect } from '@playwright/test'
import moment from 'moment'
import { test } from '@playwright/test'
import { expect } from './utils'

test('verify API call to gtfs_agencies/list - "Patterns"', async ({ page }) => {
let apiCallMade = false
page.on('request', (request) => {
if (request.url().includes('gtfs_agencies/list')) {
apiCallMade = true
}
})
test('verify API call to gtfs_agencies/list - "patterns"', async ({ page }) => {
const callAssertion = expect(page).toCall('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'דפוסי נסיעות שלא בוצעו' }).click()
await page.getByRole('link', { name: 'דפוסי נסיעות שלא בוצעו', exact: true }).click()
await page.getByLabel('חברה מפעילה').click()
expect(apiCallMade).toBeTruthy()

await callAssertion
})

test('Verify date_from parameter from "Patterns"', async ({ page }) => {
const apiRequest = page.waitForRequest((request) => request.url().includes('gtfs_agencies/list'))
test('Verify date_from parameter from "patterns"', async ({ page }) => {
const dateAssertion = expect(page).toHaveRecentDateFrom('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'דפוסי נסיעות שלא בוצעו' }).click()

const request = await apiRequest
const url = new URL(request.url())
const dateFromParam = url.searchParams.get('date_from')
const dateFrom = moment(dateFromParam)
const daysAgo = moment().diff(dateFrom, 'days')
await page.getByRole('link', { name: 'דפוסי נסיעות שלא בוצעו', exact: true }).click()

expect(daysAgo).toBeGreaterThanOrEqual(0)
expect(daysAgo).toBeLessThanOrEqual(3)
await dateAssertion
})
22 changes: 5 additions & 17 deletions tests/singlelineTest.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import moment from 'moment'
import SinglelinePage from '../src/test_pages/SinglelinePage'
import { getPastDate, test, expect, urlMatcher } from './utils'

Expand Down Expand Up @@ -123,31 +122,20 @@ test.describe('Single line page tests', () => {
})

test('verify API call to gtfs_agencies/list - "Map by line"', async ({ page }) => {
let apiCallMade = false
page.on('request', (request) => {
if (request.url().includes('gtfs_agencies/list')) {
apiCallMade = true
}
})
const callAssertion = expect(page).toCall('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'מפה לפי קו' }).click()
await page.getByLabel('חברה מפעילה').click()
expect(apiCallMade).toBeTruthy()

await callAssertion
})

test('Verify date_from parameter from "Map by line"', async ({ page }) => {
const apiRequest = page.waitForRequest((request) => request.url().includes('gtfs_agencies/list'))
const dateAssertion = expect(page).toHaveRecentDateFrom('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'מפה לפי קו' }).click()

const request = await apiRequest
const url = new URL(request.url())
const dateFromParam = url.searchParams.get('date_from')
const dateFrom = moment(dateFromParam)
const daysAgo = moment().diff(dateFrom, 'days')

expect(daysAgo).toBeGreaterThanOrEqual(0)
expect(daysAgo).toBeLessThanOrEqual(3)
await dateAssertion
})
32 changes: 10 additions & 22 deletions tests/timeline.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import i18next from 'i18next'
import Backend from 'i18next-fs-backend'

Check failure on line 2 in tests/timeline.spec.ts

View workflow job for this annotation

GitHub Actions / local-tests

'Backend' is defined but never used
import moment from 'moment'

Check failure on line 3 in tests/timeline.spec.ts

View workflow job for this annotation

GitHub Actions / local-tests

'moment' is defined but never used
import TimelinePage from '../src/test_pages/TimelinePage'
import { getPastDate, test, expect, urlMatcher, loadTranslate } from './utils'
Expand Down Expand Up @@ -133,34 +134,21 @@
})
})

test('verify API call to gtfs_agencies/list - "Trips history"', async ({ page }) => {
let apiCallMade = false
page.on('request', (request) => {
if (request.url().includes('gtfs_agencies/list')) {
apiCallMade = true
}
})
test('verify API call to gtfs_agencies/list - "trips history"', async ({ page }) => {
const callAssertion = expect(page).toCall('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'היסטוריית נסיעות' }).click()
await page.getByRole('link', { name: 'היסטוריית נסיעות', exact: true }).click()
await page.getByLabel('חברה מפעילה').click()
expect(apiCallMade).toBeTruthy()

await callAssertion
})

test('the dateFrom parameter should be recent when visiting the "Trips history"', async ({
page,
}) => {
const apiRequest = page.waitForRequest((request) => request.url().includes('gtfs_agencies/list'))
test('Verify date_from parameter from "trips history"', async ({ page }) => {
const dateAssertion = expect(page).toHaveRecentDateFrom('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'היסטוריית נסיעות' }).click()

const request = await apiRequest
const url = new URL(request.url())
const dateFromParam = url.searchParams.get('date_from')
const dateFrom = moment(dateFromParam)
const daysAgo = moment().diff(dateFrom, 'days')
await page.getByRole('link', { name: 'היסטוריית נסיעות', exact: true }).click()

expect(daysAgo).toBeGreaterThanOrEqual(0)
expect(daysAgo).toBeLessThanOrEqual(3)
await dateAssertion
})
32 changes: 9 additions & 23 deletions tests/tripExistence.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import moment from 'moment'
import { test, expect, urlMatcher } from './utils'

test.describe('Trip Existence Page Tests', () => {
Expand Down Expand Up @@ -33,34 +32,21 @@ test.describe('Trip Existence Page Tests', () => {
})
})

test('verify API call to gtfs_agencies/list - "Planned trips"', async ({ page }) => {
let apiCallMade = false
page.on('request', (request) => {
if (request.url().includes('gtfs_agencies/list')) {
apiCallMade = true
}
})
test('verify API call to gtfs_agencies/list - "planned trips"', async ({ page }) => {
const callAssertion = expect(page).toCall('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'קיום נסיעות' }).click()
await page.getByRole('link', { name: 'קיום נסיעות', exact: true }).click()
await page.getByLabel('חברה מפעילה').click()
expect(apiCallMade).toBeTruthy()

await callAssertion
})

test('the dateFrom parameter should be recent when visiting the "Planned trips" tabs', async ({
page,
}) => {
const apiRequest = page.waitForRequest((request) => request.url().includes('gtfs_agencies/list'))
test('Verify date_from parameter from "planned trips"', async ({ page }) => {
const dateAssertion = expect(page).toHaveRecentDateFrom('gtfs_agencies/list')

await page.goto('/')
await page.getByRole('link', { name: 'קיום נסיעות' }).click()

const request = await apiRequest
const url = new URL(request.url())
const dateFromParam = url.searchParams.get('date_from')
const dateFrom = moment(dateFromParam)
const daysAgo = moment().diff(dateFrom, 'days')
await page.getByRole('link', { name: 'קיום נסיעות', exact: true }).click()

expect(daysAgo).toBeGreaterThanOrEqual(0)
expect(daysAgo).toBeLessThanOrEqual(3)
await dateAssertion
})
94 changes: 93 additions & 1 deletion tests/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import * as crypto from 'crypto'
import { exec } from 'child_process'
import { Matcher, test as baseTest, customMatcher } from 'playwright-advanced-har'
import { BrowserContext, Page } from '@playwright/test'
import { BrowserContext, Page, expect as baseExpect } from '@playwright/test'
import moment from 'moment'
import { i18n } from 'i18next'
import Backend from 'i18next-fs-backend'

Expand Down Expand Up @@ -86,6 +87,97 @@
})
})

interface CustomMatcherResult {
message: () => string
pass: boolean
}

export const expect = baseExpect.extend({

Check failure on line 95 in tests/utils.ts

View workflow job for this annotation

GitHub Actions / build

Cannot redeclare block-scoped variable 'expect'.

Check failure on line 95 in tests/utils.ts

View workflow job for this annotation

GitHub Actions / build-outside-docker

Cannot redeclare block-scoped variable 'expect'.
async toCall(page: Page, urlPart: string) {
let requestFound = false

const listener = (request: { url(): string }) => {
if (request.url().includes(urlPart)) {
requestFound = true
}
}

page.on('request', listener)

const checkPromise = await new Promise<boolean>((resolve) => {
const checkInterval = setInterval(() => {
if (requestFound) {
clearInterval(checkInterval)
page.removeListener('request', listener)
resolve(true)
}
}, 100)

setTimeout(() => {
clearInterval(checkInterval)
page.removeListener('request', listener)
resolve(false)
}, 10000)
})

return {
message: () => `Expected page to make a request to ${urlPart}`,
pass: true,
async then(resolve: (result: CustomMatcherResult) => void) {
await Promise.resolve()
resolve({
message: () => `Expected page to make a request to ${urlPart}`,
pass: checkPromise,
})
},
} as CustomMatcherResult
},

async toHaveRecentDateFrom(page: Page, urlPart: string, maxDaysAgo: number = 3) {
const request = await page.waitForRequest((request: { url(): string }) =>
request.url().includes(urlPart),
)

return {
message: () =>
`Expected page to make a request to ${urlPart} with recent date_from parameter`,
pass: true,
async then(resolve: (result: CustomMatcherResult) => void) {
await Promise.resolve()

try {
const url = new URL(request.url())
const dateFromParam = url.searchParams.get('date_from')

if (!dateFromParam) {
throw new Error('date_from parameter not found')
}

const dateFrom = moment(dateFromParam)
const daysAgo = moment().diff(dateFrom, 'days')

console.log(`Request to ${urlPart}, dateFromParam: ${dateFromParam}, daysAgo: ${daysAgo}`)

const isRecent = daysAgo >= 0 && daysAgo <= maxDaysAgo

resolve({
message: () =>
`Expected date_from parameter to be within ${maxDaysAgo} days ` +
`(actual: ${daysAgo} days ago, date: ${dateFromParam})`,
pass: isRecent,
})
} catch (error) {
resolve({
message: () =>
`Failed to capture request to ${urlPart}: ${error instanceof Error ? error.message : String(error)}`,
pass: false,
})
}
},
} as CustomMatcherResult
},
})

export const waitForSkeletonsToHide = async (page: Page) => {
while ((await page.locator('.ant-skeleton-content').count()) > 0) {
await page.locator('.ant-skeleton-content').last().waitFor({ state: 'hidden' })
Expand All @@ -102,4 +194,4 @@
})
}

export const expect = test.expect

Check failure on line 197 in tests/utils.ts

View workflow job for this annotation

GitHub Actions / build

Cannot redeclare block-scoped variable 'expect'.

Check failure on line 197 in tests/utils.ts

View workflow job for this annotation

GitHub Actions / build-outside-docker

Cannot redeclare block-scoped variable 'expect'.
Loading