| 493 | } |
| 494 | |
| 495 | export async function pollFor<T>(page: playwright.Page, evalOrFn: string | (() => MaybeAsync<T>), val: T, preFn?: () => Promise<void>, options?: IPollForOptions<T>): Promise<void> { |
| 496 | if (!options) { |
| 497 | options = {}; |
| 498 | } |
| 499 | options.stack ??= new Error().stack; |
| 500 | if (preFn) { |
| 501 | await preFn(); |
| 502 | } |
| 503 | const result = typeof evalOrFn === 'string' ? await page.evaluate(evalOrFn) : await evalOrFn(); |
| 504 | |
| 505 | if (process.env.DEBUG) { |
| 506 | console.log('pollFor\n actual: ', JSON.stringify(result), ' expected: ', JSON.stringify(val)); |
| 507 | } |
| 508 | |
| 509 | let equalityCheck: boolean; |
| 510 | if (options.equalityFn) { |
| 511 | equalityCheck = options.equalityFn(result as T, val); |
| 512 | } else { |
| 513 | equalityCheck = true; |
| 514 | try { |
| 515 | deepStrictEqual(result, val); |
| 516 | } catch (e) { |
| 517 | equalityCheck = false; |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | if (!equalityCheck) { |
| 522 | if (options.maxDuration === undefined) { |
| 523 | options.maxDuration = 2000; |
| 524 | } |
| 525 | if (options.maxDuration <= 0) { |
| 526 | deepStrictEqual(result, val, ([ |
| 527 | `pollFor max duration exceeded.`, |
| 528 | (`Last comparison: ` + |
| 529 | `${typeof result === 'object' ? JSON.stringify(result) : result} (actual) !== ` + |
| 530 | `${typeof val === 'object' ? JSON.stringify(val) : val} (expected)`), |
| 531 | `Stack: ${options.stack}` |
| 532 | ].join('\n'))); |
| 533 | } |
| 534 | return new Promise<void>(r => { |
| 535 | setTimeout(() => r(pollFor(page, evalOrFn, val, preFn, { |
| 536 | ...options, |
| 537 | maxDuration: options!.maxDuration! - 10, |
| 538 | stack: options!.stack |
| 539 | })), 10); |
| 540 | }); |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | export async function pollForApproximate<T>(page: playwright.Page, marginOfError: number, evalOrFn: string | (() => MaybeAsync<T>), val: T, preFn?: () => Promise<void>, maxDuration?: number, stack?: string): Promise<void> { |
| 545 | await pollFor(page, evalOrFn, val, preFn, { |