2022-04-05 18:38:23 +00:00
|
|
|
import { expect } from 'vitest'
|
2022-10-08 14:18:57 +00:00
|
|
|
import type { Page } from 'playwright'
|
|
|
|
import { createPage, getBrowser, url, useTestContext } from '@nuxt/test-utils'
|
2022-04-05 18:38:23 +00:00
|
|
|
|
|
|
|
export async function renderPage (path = '/') {
|
2022-04-07 11:28:04 +00:00
|
|
|
const ctx = useTestContext()
|
|
|
|
if (!ctx.options.browser) {
|
2022-08-26 15:47:29 +00:00
|
|
|
throw new Error('`renderPage` require `options.browser` to be set')
|
2022-04-07 11:28:04 +00:00
|
|
|
}
|
|
|
|
|
2022-04-05 18:38:23 +00:00
|
|
|
const browser = await getBrowser()
|
|
|
|
const page = await browser.newPage({})
|
2022-08-26 15:47:29 +00:00
|
|
|
const pageErrors: Error[] = []
|
2022-10-08 14:18:57 +00:00
|
|
|
const consoleLogs: { type: string, text: string }[] = []
|
2022-04-05 18:38:23 +00:00
|
|
|
|
|
|
|
page.on('console', (message) => {
|
|
|
|
consoleLogs.push({
|
|
|
|
type: message.type(),
|
|
|
|
text: message.text()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
page.on('pageerror', (err) => {
|
|
|
|
pageErrors.push(err)
|
|
|
|
})
|
|
|
|
|
|
|
|
if (path) {
|
|
|
|
await page.goto(url(path), { waitUntil: 'networkidle' })
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
page,
|
|
|
|
pageErrors,
|
|
|
|
consoleLogs
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function expectNoClientErrors (path: string) {
|
2022-04-07 11:28:04 +00:00
|
|
|
const ctx = useTestContext()
|
|
|
|
if (!ctx.options.browser) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-08-26 15:47:29 +00:00
|
|
|
const { pageErrors, consoleLogs } = (await renderPage(path))!
|
2022-04-05 18:38:23 +00:00
|
|
|
|
|
|
|
const consoleLogErrors = consoleLogs.filter(i => i.type === 'error')
|
2022-07-29 12:50:02 +00:00
|
|
|
const consoleLogWarnings = consoleLogs.filter(i => i.type === 'warning')
|
2022-04-05 18:38:23 +00:00
|
|
|
|
|
|
|
expect(pageErrors).toEqual([])
|
|
|
|
expect(consoleLogErrors).toEqual([])
|
|
|
|
expect(consoleLogWarnings).toEqual([])
|
|
|
|
}
|
2022-10-08 14:18:57 +00:00
|
|
|
|
|
|
|
export async function withLogs (callback: (page: Page, logs: string[]) => Promise<void>) {
|
|
|
|
let done = false
|
|
|
|
const page = await createPage()
|
|
|
|
const logs: string[] = []
|
|
|
|
page.on('console', (msg) => {
|
|
|
|
const text = msg.text()
|
|
|
|
if (done) {
|
|
|
|
throw new Error('Test finished prematurely')
|
|
|
|
}
|
|
|
|
logs.push(text)
|
|
|
|
})
|
|
|
|
|
|
|
|
try {
|
|
|
|
await callback(page, logs)
|
|
|
|
} finally {
|
|
|
|
done = true
|
|
|
|
}
|
|
|
|
}
|