fixtures.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 { autocompleteMenu, 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. const rightSidebar = page.locator('.cp__right-sidebar-inner')
  91. if (await rightSidebar.isVisible()) {
  92. await page.click('button.toggle-right-sidebar', {delay: 100})
  93. }
  94. }
  95. })
  96. base.afterAll(async () => {
  97. // if (electronApp) {
  98. // await electronApp.close()
  99. //}
  100. })
  101. // hijack electron app into the test context
  102. // FIXME: add type to `block`
  103. export const test = base.extend<LogseqFixtures>({
  104. page: async ({ }, use) => {
  105. await use(page);
  106. },
  107. // Timeout is used to avoid global timeout, local timeout will have a meaningful error report.
  108. // 1s timeout is enough for most of the test cases.
  109. // Timeout won't introduce additional sleeps.
  110. block: async ({ page }, use) => {
  111. const block = {
  112. mustFill: async (value: string) => {
  113. const locator: Locator = page.locator('textarea >> nth=0')
  114. await locator.waitFor({ timeout: 1000 })
  115. await locator.fill(value)
  116. await expect(locator).toHaveText(value, { timeout: 1000 })
  117. },
  118. mustType: async (value: string, options?: { delay?: number, toBe?: string }) => {
  119. const locator: Locator = page.locator('textarea >> nth=0')
  120. await locator.waitFor({ timeout: 1000 })
  121. const { delay = 50 } = options || {};
  122. const { toBe = value } = options || {};
  123. await locator.type(value, { delay })
  124. await expect(locator).toHaveText(toBe, { timeout: 1000 })
  125. },
  126. enterNext: async (): Promise<Locator> => {
  127. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  128. await page.press('textarea >> nth=0', 'Enter')
  129. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible', timeout: 1000 })
  130. return page.locator('textarea >> nth=0')
  131. },
  132. clickNext: async (): Promise<Locator> => {
  133. await page.$eval('.add-button-link-wrap', (element) => {
  134. element.scrollIntoView();
  135. });
  136. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  137. // the next element after all blocks.
  138. await page.click('.add-button-link-wrap', { delay: 100 })
  139. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible', timeout: 1000 })
  140. return page.locator('textarea >> nth=0')
  141. },
  142. indent: async (): Promise<boolean> => {
  143. const locator = page.locator('textarea >> nth=0')
  144. const before = await locator.boundingBox()
  145. await locator.press('Tab', { delay: 100 })
  146. return (await locator.boundingBox()).x > before.x
  147. },
  148. unindent: async (): Promise<boolean> => {
  149. const locator = page.locator('textarea >> nth=0')
  150. const before = await locator.boundingBox()
  151. await locator.press('Shift+Tab', { delay: 100 })
  152. return (await locator.boundingBox()).x < before.x
  153. },
  154. waitForBlocks: async (total: number): Promise<void> => {
  155. // NOTE: `nth=` counts from 0.
  156. await page.waitForSelector(`.ls-block >> nth=${total - 1}`, { state: 'attached', timeout: 50000 })
  157. await page.waitForSelector(`.ls-block >> nth=${total}`, { state: 'detached', timeout: 50000 })
  158. },
  159. waitForSelectedBlocks: async (total: number): Promise<void> => {
  160. // NOTE: `nth=` counts from 0.
  161. await page.waitForSelector(`.ls-block.selected >> nth=${total - 1}`, { timeout: 1000 })
  162. },
  163. escapeEditing: async (): Promise<void> => {
  164. await page.keyboard.press('Escape')
  165. await page.keyboard.press('Escape')
  166. },
  167. activeEditing: async (nth: number): Promise<void> => {
  168. await page.waitForSelector(`.ls-block >> nth=${nth}`, { timeout: 1000 })
  169. // scroll, for isVisble test
  170. await page.$eval(`.ls-block >> nth=${nth}`, (element) => {
  171. element.scrollIntoView();
  172. });
  173. // when blocks are nested, the first block(the parent) is selected.
  174. if (
  175. (await page.isVisible(`.ls-block >> nth=${nth} >> .editor-wrapper >> textarea`)) &&
  176. !(await page.isVisible(`.ls-block >> nth=${nth} >> .block-children-container >> textarea`))) {
  177. return;
  178. }
  179. await page.click(`.ls-block >> nth=${nth} >> .block-content`, { delay: 10, timeout: 100000 })
  180. await page.waitForSelector(`.ls-block >> nth=${nth} >> .editor-wrapper >> textarea`, { timeout: 1000, state: 'visible' })
  181. },
  182. isEditing: async (): Promise<boolean> => {
  183. const locator = page.locator('.ls-block textarea >> nth=0')
  184. return await locator.isVisible()
  185. },
  186. selectionStart: async (): Promise<number> => {
  187. return await page.locator('textarea >> nth=0').evaluate(node => {
  188. const elem = <HTMLTextAreaElement>node
  189. return elem.selectionStart
  190. })
  191. },
  192. selectionEnd: async (): Promise<number> => {
  193. return await page.locator('textarea >> nth=0').evaluate(node => {
  194. const elem = <HTMLTextAreaElement>node
  195. return elem.selectionEnd
  196. })
  197. }
  198. }
  199. use(block)
  200. },
  201. autocompleteMenu: async ({ }, use) => {
  202. const autocompleteMenu: autocompleteMenu = {
  203. expectVisible: async (modalName?: string) => {
  204. const modal = page.locator(modalName ? `[data-modal-name="${modalName}"]` : `[data-modal-name]`)
  205. if (await modal.isVisible()) {
  206. await page.waitForTimeout(100)
  207. await expect(modal).toBeVisible()
  208. } else {
  209. await modal.waitFor({ state: 'visible', timeout: 1000 })
  210. }
  211. },
  212. expectHidden: async (modalName?: string) => {
  213. const modal = page.locator(modalName ? `[data-modal-name="${modalName}"]` : `[data-modal-name]`)
  214. if (!await modal.isVisible()) {
  215. await page.waitForTimeout(100)
  216. await expect(modal).not.toBeVisible()
  217. } else {
  218. await modal.waitFor({ state: 'hidden', timeout: 1000 })
  219. }
  220. }
  221. }
  222. await use(autocompleteMenu)
  223. },
  224. context: async ({ }, use) => {
  225. await use(context);
  226. },
  227. app: async ({ }, use) => {
  228. await use(electronApp);
  229. },
  230. graphDir: async ({ }, use) => {
  231. await use(graphDir);
  232. },
  233. });