diff --git a/tests/playwright/page/Index.ts b/tests/playwright/page/Index.ts index 23a99505..786820c0 100644 --- a/tests/playwright/page/Index.ts +++ b/tests/playwright/page/Index.ts @@ -2,6 +2,7 @@ import { expect, Page } from "@playwright/test"; import * as fs from "fs"; import AdvancedSearch from "@hipanel-core/helper/AdvancedSearch"; import { Alert, BulkActions, ColumnFilters } from "@hipanel-core/shared/ui/components"; +import {Download} from "@playwright/test"; export default class Index { advancedSearch: AdvancedSearch; @@ -212,30 +213,69 @@ export default class Index { } } - private async checkDownloadByLinkName(linkName: string) { - const linkLocator = this.page.locator(`a:has-text("${linkName}")`); + private async checkDownloadByLinkName(linkName: string): Promise { + const download = await this.triggerDownloadByLinkName(linkName); + const downloadPath = this.buildDownloadPath(download); - await linkLocator.highlight(); + await this.saveDownload(download, downloadPath); - const [download] = await Promise.all([ - this.page.waitForEvent("download"), - linkLocator.click(), - ]); + await this.waitForFile(downloadPath); + } + + private async triggerDownloadByLinkName(linkName: string) { + const downloadPromise = this.page.waitForEvent('download'); - const downloadPath = `runtime/${download.suggestedFilename()}`; - await download.saveAs(downloadPath); + const link = this.page.locator(`a:has-text("${linkName}")`); + await link.highlight(); + await link.click(); - const fileExissts = fs.existsSync(downloadPath); - const stats = fs.statSync(downloadPath); + const download = await downloadPromise; - const path = await download.path(); + return download; + } + + private buildDownloadPath(download: Download): string { + return `runtime/${download.suggestedFilename()}`; + } - console.log("Temporary path:", path); + private async saveDownload(download: Download, filePath: string): Promise { + await download.saveAs(filePath); - expect(fileExissts, `File not found at path: ${downloadPath}`).toBeTruthy(); + console.log("Temporary download path:", await download.path()); + } + + private async waitForFile(filePath: string, timeoutMs = 5000): Promise { + const pollingIntervalMs = 100; + const deadline = Date.now() + timeoutMs; + + while (Date.now() < deadline) { + if (this.isFileReady(filePath)) { + return; + } - console.log(`File ${path}: ${stats.size} bytes`); + console.log(`Waiting for file to be ready: ${filePath}`); + await this.delay(pollingIntervalMs); + } + + throw new Error(`Timed out waiting for file: ${filePath}`); + } + + private isFileReady(filePath: string): boolean { + if (!fs.existsSync(filePath)) { + return false; + } + + const { size } = fs.statSync(filePath); + + if (size > 0) { + console.log(`Downloaded file ready: ${filePath} (${size} bytes)`); + return true; + } + + return false; + } - expect(stats.size).toBeGreaterThan(0); + private delay(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); } }