12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- // cypress/support/e2e.ts
- // Import commands.js using ES2015 syntax:
- import './commands';
- import './mock/index';
- import './pageObjects/LoginPage';
- import './pageObjects/MainPage';
- import './pageObjects/WorklistPage';
- // Alternatively you can use CommonJS syntax:
- // require('./commands')
- // require('./pageObjects/LoginPage')
- // 拦截浏览器 console 日志并输出到终端
- // 使用 CDP (Chrome DevTools Protocol) 来监听 console 事件
- Cypress.on('window:before:load', (win) => {
- // 保存原始的 console 方法
- const originalLog = win.console.log
- const originalError = win.console.error
- const originalWarn = win.console.warn
-
- // 在 window 对象上创建日志缓冲区
- if (!win.__consoleLogs__) {
- win.__consoleLogs__ = []
- }
-
- // 重写 console.log - 存储到缓冲区
- win.console.log = function(...args: any[]) {
- originalLog.apply(win.console, args)
- const message = args.map(arg =>
- typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
- ).join(' ')
- win.__consoleLogs__.push({ type: 'log', message, timestamp: new Date().toISOString() })
- }
-
- // 重写 console.error
- win.console.error = function(...args: any[]) {
- originalError.apply(win.console, args)
- const message = args.map(arg =>
- typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
- ).join(' ')
- win.__consoleLogs__.push({ type: 'error', message, timestamp: new Date().toISOString() })
- }
-
- // 重写 console.warn
- win.console.warn = function(...args: any[]) {
- originalWarn.apply(win.console, args)
- const message = args.map(arg =>
- typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
- ).join(' ')
- win.__consoleLogs__.push({ type: 'warn', message, timestamp: new Date().toISOString() })
- }
- })
- // 添加自定义命令来刷新日志到终端
- Cypress.Commands.add('flushConsoleLogs', () => {
- cy.window({ log: false }).then((win: any) => {
- if (win.__consoleLogs__ && win.__consoleLogs__.length > 0) {
- const logs = win.__consoleLogs__.splice(0) // 清空缓冲区
- logs.forEach((log: any) => {
- const prefix = log.type === 'error' ? '[ERROR] ' : log.type === 'warn' ? '[WARN] ' : ''
- cy.task('browserLog', `${prefix}${log.message}`, { log: false })
- })
- }
- })
- })
- // 自动在每个测试后刷新日志
- afterEach(() => {
- cy.flushConsoleLogs()
- })
|