Skip to content

Commit

Permalink
✨ feat(core): Add waitForExtensionOnLoadPage function (#954)
Browse files Browse the repository at this point in the history
  • Loading branch information
duckception authored Oct 25, 2023
1 parent d488acf commit 3f5b549
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/core/src/utils/waitForExtensionOnLoadPage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { type BrowserContext, errors as playwrightErrors } from 'playwright-core'

export async function waitForExtensionOnLoadPage(context: BrowserContext) {
try {
return await context.waitForEvent('page', { timeout: 5000 }) // TODO: Extract & Make this timeout configurable.
} catch (e) {
if (e instanceof playwrightErrors.TimeoutError) {
throw new Error('[WaitForExtensionOnLoadPage] Extension did not load in time!')
}

throw e
}
}
53 changes: 53 additions & 0 deletions packages/core/test/utils/waitForExtensionOnLoadPage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { errors as playwrightErrors } from 'playwright-core'
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'
import { waitForExtensionOnLoadPage } from '../../src/utils/waitForExtensionOnLoadPage'

const createContext = vi.fn().mockReturnValue({
waitForEvent: vi.fn().mockResolvedValue(undefined)
})

const createTimeoutContext = vi.fn().mockReturnValue({
waitForEvent: vi.fn().mockImplementation(() => {
throw new playwrightErrors.TimeoutError('Timeout :)')
})
})

const createThrowContext = vi.fn().mockReturnValue({
waitForEvent: vi.fn().mockImplementation(() => {
throw new Error('Unknown Quack!')
})
})

describe('waitForExtensionOnLoadPage', () => {
afterAll(() => {
vi.resetAllMocks()
})

afterEach(() => {
vi.clearAllMocks()
})

it('calls context.waitForEvent with correct arguments', async () => {
const context = createContext()
const waitForEventSpy = vi.spyOn(context, 'waitForEvent')

await waitForExtensionOnLoadPage(context)

expect(waitForEventSpy).toHaveBeenCalledOnce()
expect(waitForEventSpy).toHaveBeenCalledWith('page', { timeout: 5000 })
})

it('throws with custom error if waitForEvent throws due to timeout', async () => {
const context = createTimeoutContext()

await expect(waitForExtensionOnLoadPage(context)).rejects.toThrowError(
'[WaitForExtensionOnLoadPage] Extension did not load in time!'
)
})

it('throws if unknown error', async () => {
const context = createThrowContext()

await expect(waitForExtensionOnLoadPage(context)).rejects.toThrowError('Unknown Quack!')
})
})

0 comments on commit 3f5b549

Please sign in to comment.