2017-01-12 04:14:49 +00:00
|
|
|
import wd from 'wd'
|
|
|
|
|
|
|
|
export default async function (appPort, pathname) {
|
2018-04-12 07:47:42 +00:00
|
|
|
if (typeof appPort === 'undefined') {
|
|
|
|
throw new Error('appPort is undefined')
|
|
|
|
}
|
|
|
|
|
2017-01-12 04:14:49 +00:00
|
|
|
const url = `http://localhost:${appPort}${pathname}`
|
2017-03-08 07:53:05 +00:00
|
|
|
console.log(`> Start loading browser with url: ${url}`)
|
2017-01-12 04:14:49 +00:00
|
|
|
|
2017-03-08 07:53:05 +00:00
|
|
|
// Sometimes browser won't initialize due to some random issues.
|
|
|
|
// So, we need to timeout the initialization and retry again.
|
|
|
|
for (let lc = 0; lc < 5; lc++) {
|
|
|
|
try {
|
|
|
|
const browser = await getBrowser(url, 5000)
|
|
|
|
console.log(`> Complete loading browser with url: ${url}`)
|
|
|
|
return browser
|
|
|
|
} catch (ex) {
|
|
|
|
console.warn(`> Error when loading browser with url: ${url}`)
|
|
|
|
if (ex.message === 'TIMEOUT') continue
|
|
|
|
throw ex
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
console.error(`> Tried 5 times. Cannot load the browser for url: ${url}`)
|
|
|
|
throw new Error(`Couldn't start the browser for url: ${url}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
function getBrowser (url, timeout) {
|
2017-01-12 04:14:49 +00:00
|
|
|
const browser = wd.promiseChainRemote('http://localhost:9515/')
|
|
|
|
|
2017-03-08 07:53:05 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
let timeouted = false
|
|
|
|
const timeoutHandler = setTimeout(() => {
|
|
|
|
timeouted = true
|
|
|
|
const error = new Error('TIMEOUT')
|
|
|
|
reject(error)
|
|
|
|
}, timeout)
|
|
|
|
|
|
|
|
browser.init({browserName: 'chrome'}).get(url, (err) => {
|
|
|
|
if (timeouted) {
|
|
|
|
browser.close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
clearTimeout(timeoutHandler)
|
|
|
|
|
|
|
|
if (err) {
|
|
|
|
reject(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve(browser)
|
|
|
|
})
|
|
|
|
})
|
2017-01-12 04:14:49 +00:00
|
|
|
}
|