/ tests / testUtil.mts
testUtil.mts
 1  import { Page } from 'playwright'
 2  import { TestInfo } from 'playwright/test'
 3  
 4  export default class TestUtil {
 5    _page: Page
 6  
 7    _testInfo: TestInfo
 8  
 9    _testScreenshotPath: string
10  
11    constructor(page: Page, testInfo: TestInfo, testScreenshotPath: string) {
12      this._page = page
13      this._testInfo = testInfo
14      this._testScreenshotPath = testScreenshotPath
15    }
16  
17    async captureScreenshot(pageInstance: Page, screenshotName: string) {
18      if (!pageInstance) {
19        return
20      }
21  
22      try {
23        const screenshotPath = `${this._testScreenshotPath}/${screenshotName || `unknown_${Date.now()}`}.png`
24  
25        await pageInstance.screenshot({ path: screenshotPath })
26      } catch (error) {
27        // Do nothing
28      }
29    }
30  
31    async onTestError(error: Error) {
32      const titleLists = [...this._testInfo.titlePath]
33      titleLists.shift()
34      const title = titleLists.join('-')
35  
36      await this.captureScreenshot(this._page, `${title}_${Date.now()}`)
37  
38      return new Error(error.message)
39    }
40  }