|
| 1 | +export class UrlNotYetAvailableError extends Error { |
| 2 | + constructor () { |
| 3 | + const message = 'URL is not yet available' |
| 4 | + |
| 5 | + super(message) |
| 6 | + this.name = 'UrlNotYetAvailableError' |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +export function getUrlFromAutomation (Cypress: Cypress.Cypress, options: Partial<Cypress.Loggable & Cypress.Timeoutable> = {}) { |
| 11 | + const timeout = options.timeout ?? Cypress.config('defaultCommandTimeout') as number |
| 12 | + |
| 13 | + this.set('timeout', timeout) |
| 14 | + |
| 15 | + let fullUrlObj: any = null |
| 16 | + let automationPromise: Promise<void> | null = null |
| 17 | + // need to set a valid type on this |
| 18 | + let mostRecentError = new UrlNotYetAvailableError() |
| 19 | + |
| 20 | + const getUrlFromAutomation = () => { |
| 21 | + if (automationPromise) { |
| 22 | + return automationPromise |
| 23 | + } |
| 24 | + |
| 25 | + fullUrlObj = null |
| 26 | + |
| 27 | + automationPromise = Cypress.automation('get:aut:url', {}) |
| 28 | + .timeout(timeout) |
| 29 | + .then((url) => { |
| 30 | + const fullUrlObject = new URL(url) |
| 31 | + |
| 32 | + fullUrlObj = { |
| 33 | + hash: fullUrlObject.hash, |
| 34 | + host: fullUrlObject.host, |
| 35 | + hostname: fullUrlObject.hostname, |
| 36 | + href: fullUrlObject.href, |
| 37 | + origin: fullUrlObject.origin, |
| 38 | + pathname: fullUrlObject.pathname, |
| 39 | + port: fullUrlObject.port, |
| 40 | + protocol: fullUrlObject.protocol, |
| 41 | + search: fullUrlObject.search, |
| 42 | + searchParams: fullUrlObject.searchParams, |
| 43 | + } |
| 44 | + }) |
| 45 | + .catch((err) => { |
| 46 | + mostRecentError.name = err.name |
| 47 | + mostRecentError.message = err.message |
| 48 | + }) |
| 49 | + .catch((err) => mostRecentError = err) |
| 50 | + // Pass or fail, we always clear the automationPromise, so future retries know there's no live request to the server. |
| 51 | + .finally(() => automationPromise = null) |
| 52 | + |
| 53 | + return automationPromise |
| 54 | + } |
| 55 | + |
| 56 | + this.set('onFail', (err) => { |
| 57 | + // if we are actively retrying or the assertion failed, we want to retry |
| 58 | + if (err.name === 'UrlNotYetAvailableError' || err.name === 'AssertionError') { |
| 59 | + // tslint:disable-next-line no-floating-promises |
| 60 | + getUrlFromAutomation() |
| 61 | + } else { |
| 62 | + throw err |
| 63 | + } |
| 64 | + }) |
| 65 | + |
| 66 | + return () => { |
| 67 | + if (fullUrlObj) { |
| 68 | + return fullUrlObj |
| 69 | + } |
| 70 | + |
| 71 | + // tslint:disable-next-line no-floating-promises |
| 72 | + getUrlFromAutomation() |
| 73 | + |
| 74 | + throw mostRecentError |
| 75 | + } |
| 76 | +} |
0 commit comments