fixtures.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import * as fs from 'fs'
  2. import * as path from 'path'
  3. import { test as base, expect, ConsoleMessage, Locator } from '@playwright/test';
  4. import { ElectronApplication, Page, BrowserContext, _electron as electron } from 'playwright'
  5. import { loadLocalGraph, openLeftSidebar, randomString } from './utils';
  6. import { LogseqFixtures } from './types';
  7. let electronApp: ElectronApplication
  8. let context: BrowserContext
  9. let page: Page
  10. let repoName = randomString(10)
  11. let testTmpDir = path.resolve(__dirname, '../tmp')
  12. if (fs.existsSync(testTmpDir)) {
  13. fs.rmSync(testTmpDir, { recursive: true })
  14. }
  15. export let graphDir = path.resolve(testTmpDir, "e2e-test", repoName)
  16. // NOTE: This following is a console log watcher for error logs.
  17. // Save and print all logs when error happens.
  18. let logs: string
  19. const consoleLogWatcher = (msg: ConsoleMessage) => {
  20. // console.log(msg.text())
  21. const text = msg.text()
  22. logs += text + '\n'
  23. expect(text, logs).not.toMatch(/^(Failed to|Uncaught)/)
  24. // youtube video
  25. if (!text.match(/^Error with Permissions-Policy header: Unrecognized feature/)) {
  26. expect(text, logs).not.toMatch(/^Error/)
  27. }
  28. // NOTE: React warnings will be logged as error.
  29. // expect(msg.type()).not.toBe('error')
  30. }
  31. base.beforeAll(async () => {
  32. if (electronApp) {
  33. return
  34. }
  35. console.log(`Creating test graph directory: ${graphDir}`)
  36. fs.mkdirSync(graphDir, {
  37. recursive: true,
  38. });
  39. electronApp = await electron.launch({
  40. cwd: "./static",
  41. args: ["electron.js"],
  42. locale: 'en',
  43. timeout: 10_000, // should be enough for the app to start
  44. })
  45. context = electronApp.context()
  46. await context.tracing.start({ screenshots: true, snapshots: true });
  47. // NOTE: The following ensures App first start with the correct path.
  48. const info = await electronApp.evaluate(async ({ app }) => {
  49. return {
  50. "appPath": app.getAppPath(),
  51. "appData": app.getPath("appData"),
  52. "userData": app.getPath("userData"),
  53. "appName": app.getName(),
  54. "electronVersion": app.getVersion(),
  55. }
  56. })
  57. console.log("Test start with:", info)
  58. page = await electronApp.firstWindow()
  59. // Direct Electron console to watcher
  60. page.on('console', consoleLogWatcher)
  61. page.on('crash', () => {
  62. expect(false, "Page must not crash").toBeTruthy()
  63. })
  64. page.on('pageerror', (err) => {
  65. console.log(err)
  66. // expect(false, 'Page must not have errors!').toBeTruthy()
  67. })
  68. await page.waitForLoadState('domcontentloaded')
  69. // NOTE: The following ensures first start.
  70. // await page.waitForSelector('text=This is a demo graph, changes will not be saved until you open a local folder')
  71. await page.waitForSelector(':has-text("Loading")', {
  72. state: "hidden",
  73. timeout: 1000 * 15,
  74. });
  75. page.once('load', async () => {
  76. console.log('Page loaded!')
  77. await page.screenshot({ path: 'startup.png' })
  78. })
  79. await loadLocalGraph(page, graphDir);
  80. // render app
  81. await page.waitForFunction('window.document.title !== "Loading"')
  82. expect(await page.title()).toMatch(/^Logseq.*?/)
  83. await openLeftSidebar(page)
  84. })
  85. base.beforeEach(async () => {
  86. // discard any dialog by ESC
  87. if (page) {
  88. await page.keyboard.press('Escape')
  89. await page.keyboard.press('Escape')
  90. }
  91. })
  92. base.afterAll(async () => {
  93. // if (electronApp) {
  94. // await electronApp.close()
  95. //}
  96. })
  97. // hijack electron app into the test context
  98. // FIXME: add type to `block`
  99. export const test = base.extend<LogseqFixtures>({
  100. page: async ({ }, use) => {
  101. await use(page);
  102. },
  103. // Timeout is used to avoid global timeout, local timeout will have a meaningful error report.
  104. // 1s timeout is enough for most of the test cases.
  105. // Timeout won't introduce additional sleeps.
  106. block: async ({ page }, use) => {
  107. const block = {
  108. mustFill: async (value: string) => {
  109. const locator: Locator = page.locator('textarea >> nth=0')
  110. await locator.waitFor({ timeout: 1000 })
  111. await locator.fill(value)
  112. await expect(locator).toHaveText(value, { timeout: 1000 })
  113. },
  114. mustType: async (value: string, options?: { delay?: number, toBe?: string }) => {
  115. const locator: Locator = page.locator('textarea >> nth=0')
  116. await locator.waitFor({ timeout: 1000 })
  117. const { delay = 50 } = options || {};
  118. const { toBe = value } = options || {};
  119. await locator.type(value, { delay })
  120. await expect(locator).toHaveText(toBe, { timeout: 1000 })
  121. },
  122. enterNext: async (): Promise<Locator> => {
  123. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  124. await page.press('textarea >> nth=0', 'Enter')
  125. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible', timeout: 1000 })
  126. return page.locator('textarea >> nth=0')
  127. },
  128. clickNext: async (): Promise<Locator> => {
  129. await page.$eval('.add-button-link-wrap', (element) => {
  130. element.scrollIntoView();
  131. });
  132. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  133. // the next element after all blocks.
  134. await page.click('.add-button-link-wrap', { delay: 100 })
  135. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible', timeout: 1000 })
  136. return page.locator('textarea >> nth=0')
  137. },
  138. indent: async (): Promise<boolean> => {
  139. const locator = page.locator('textarea >> nth=0')
  140. const before = await locator.boundingBox()
  141. await locator.press('Tab', { delay: 100 })
  142. return (await locator.boundingBox()).x > before.x
  143. },
  144. unindent: async (): Promise<boolean> => {
  145. const locator = page.locator('textarea >> nth=0')
  146. const before = await locator.boundingBox()
  147. await locator.press('Shift+Tab', { delay: 100 })
  148. return (await locator.boundingBox()).x < before.x
  149. },
  150. waitForBlocks: async (total: number): Promise<void> => {
  151. // NOTE: `nth=` counts from 0.
  152. await page.waitForSelector(`.ls-block >> nth=${total - 1}`, { state: 'attached', timeout: 50000 })
  153. await page.waitForSelector(`.ls-block >> nth=${total}`, { state: 'detached', timeout: 50000 })
  154. },
  155. waitForSelectedBlocks: async (total: number): Promise<void> => {
  156. // NOTE: `nth=` counts from 0.
  157. await page.waitForSelector(`.ls-block.selected >> nth=${total - 1}`, { timeout: 1000 })
  158. },
  159. escapeEditing: async (): Promise<void> => {
  160. await page.keyboard.press('Escape')
  161. await page.keyboard.press('Escape')
  162. },
  163. activeEditing: async (nth: number): Promise<void> => {
  164. await page.waitForSelector(`.ls-block >> nth=${nth}`, { timeout: 1000 })
  165. // scroll, for isVisble test
  166. await page.$eval(`.ls-block >> nth=${nth}`, (element) => {
  167. element.scrollIntoView();
  168. });
  169. // when blocks are nested, the first block(the parent) is selected.
  170. if (
  171. (await page.isVisible(`.ls-block >> nth=${nth} >> .editor-wrapper >> textarea`)) &&
  172. !(await page.isVisible(`.ls-block >> nth=${nth} >> .block-children-container >> textarea`))) {
  173. return;
  174. }
  175. await page.click(`.ls-block >> nth=${nth} >> .block-content`, { delay: 10, timeout: 100000 })
  176. await page.waitForSelector(`.ls-block >> nth=${nth} >> .editor-wrapper >> textarea`, { timeout: 1000, state: 'visible' })
  177. },
  178. isEditing: async (): Promise<boolean> => {
  179. const locator = page.locator('.ls-block textarea >> nth=0')
  180. return await locator.isVisible()
  181. },
  182. selectionStart: async (): Promise<number> => {
  183. return await page.locator('textarea >> nth=0').evaluate(node => {
  184. const elem = <HTMLTextAreaElement>node
  185. return elem.selectionStart
  186. })
  187. },
  188. selectionEnd: async (): Promise<number> => {
  189. return await page.locator('textarea >> nth=0').evaluate(node => {
  190. const elem = <HTMLTextAreaElement>node
  191. return elem.selectionEnd
  192. })
  193. }
  194. }
  195. use(block)
  196. },
  197. context: async ({ }, use) => {
  198. await use(context);
  199. },
  200. app: async ({ }, use) => {
  201. await use(electronApp);
  202. },
  203. graphDir: async ({ }, use) => {
  204. await use(graphDir);
  205. },
  206. });