e2e.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // cypress/support/e2e.ts
  2. // Import commands.js using ES2015 syntax:
  3. import './commands';
  4. import './mock/index';
  5. import './pageObjects/LoginPage';
  6. import './pageObjects/MainPage';
  7. import './pageObjects/WorklistPage';
  8. // Alternatively you can use CommonJS syntax:
  9. // require('./commands')
  10. // require('./pageObjects/LoginPage')
  11. // 拦截浏览器 console 日志并输出到终端
  12. // 使用 CDP (Chrome DevTools Protocol) 来监听 console 事件
  13. Cypress.on('window:before:load', (win) => {
  14. // 保存原始的 console 方法
  15. const originalLog = win.console.log
  16. const originalError = win.console.error
  17. const originalWarn = win.console.warn
  18. // 在 window 对象上创建日志缓冲区
  19. if (!win.__consoleLogs__) {
  20. win.__consoleLogs__ = []
  21. }
  22. // 重写 console.log - 存储到缓冲区
  23. win.console.log = function(...args: any[]) {
  24. originalLog.apply(win.console, args)
  25. const message = args.map(arg =>
  26. typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
  27. ).join(' ')
  28. win.__consoleLogs__.push({ type: 'log', message, timestamp: new Date().toISOString() })
  29. }
  30. // 重写 console.error
  31. win.console.error = function(...args: any[]) {
  32. originalError.apply(win.console, args)
  33. const message = args.map(arg =>
  34. typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
  35. ).join(' ')
  36. win.__consoleLogs__.push({ type: 'error', message, timestamp: new Date().toISOString() })
  37. }
  38. // 重写 console.warn
  39. win.console.warn = function(...args: any[]) {
  40. originalWarn.apply(win.console, args)
  41. const message = args.map(arg =>
  42. typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
  43. ).join(' ')
  44. win.__consoleLogs__.push({ type: 'warn', message, timestamp: new Date().toISOString() })
  45. }
  46. })
  47. // 添加自定义命令来刷新日志到终端
  48. Cypress.Commands.add('flushConsoleLogs', () => {
  49. cy.window({ log: false }).then((win: any) => {
  50. if (win.__consoleLogs__ && win.__consoleLogs__.length > 0) {
  51. const logs = win.__consoleLogs__.splice(0) // 清空缓冲区
  52. logs.forEach((log: any) => {
  53. const prefix = log.type === 'error' ? '[ERROR] ' : log.type === 'warn' ? '[WARN] ' : ''
  54. cy.task('browserLog', `${prefix}${log.message}`, { log: false })
  55. })
  56. }
  57. })
  58. })
  59. // 自动在每个测试后刷新日志
  60. afterEach(() => {
  61. cy.flushConsoleLogs()
  62. })