Commit f89d55f1 authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Add selenium-webdriver and testing cross-browser in PRs (#9821)

* Migrate from wd to selenium-webdriver

* Add chaining for next-webdriver

* Re-add browserStackLocal global for teardown

* Add additional element methods

* Use freshWindow helper for chrome

* Add selenium-server

* Add cross-env for windows compat

* Fix single quote windows

* Update production preload tests

* Update preload tests count

* Update CircleCi for testing other browsers

* Update CI configs

* Update config

* Add browser.url command

* Add more methods

* Update xcode version

* Make sure to add chromedriver to path

* Add forceExit flag

* Update config

* Update config

* Disable safari

* Fix bug in test

* Add teardown logging

* Update jest teardown

* Move testing ie11 to Azure

* Update job names

* Remove force exiting on long teardown

* Update Azure config

* Re-add safari testing with BrowserStack

* Update config

* Update prefetch tests for ie11

* Update prefetch for safari and ids for ie11 testing

* trigger prefetching manually in ie
parent ec440d4b
......@@ -20,10 +20,13 @@ aliases:
# Executors
#########################
orbs:
win: circleci/windows@2.2.0
executors:
node:
docker:
- image: circleci/node@sha256:8631b3dc0f49fc179940bbd4254ced0c41b99d02bfdbf1d8bdd4d0b135e3ee5f
- image: circleci/node:10-browsers
working_directory: ~/repo
#########################
......@@ -36,13 +39,6 @@ commands:
- run:
name: Installing Dependencies
command: yarn install --frozen-lockfile --check-files
- run:
name: Install correct Chrome Driver version
command: node node_modules/chromedriver/install.js
environment:
CHROMEDRIVER_VERSION: '76.0.3809.68'
- run: google-chrome --version
- run: yarn chromedriver --version
yarn_lint:
steps:
- run:
......@@ -53,8 +49,6 @@ commands:
- run:
name: Upgrade to most recent release in React's Next channel
command: yarn upgrade react@next react-dom@next -W --dev # upgrade (vs add) will skip re-building Next.js, which doesn't bundle React internals (so this is OK!)
environment:
CHROMEDRIVER_VERSION: '76.0.3809.68'
yarn_info:
steps:
- run:
......@@ -62,6 +56,8 @@ commands:
command: yarn why react && yarn why react-dom
test_all:
steps:
- run: google-chrome --version
- run: chromedriver --version
- run:
name: Run All Tests
command: |
......@@ -71,22 +67,22 @@ commands:
)
environment:
NEXT_TELEMETRY_DISABLED: '1'
test_browser:
parameters:
browser:
type: string
test_safari:
steps:
- run:
name: Test in a browser
name: Test Safari
command: |
if [[ ! -z $BROWSERSTACK_USERNAME ]]; then
yarn testall test/integration/production/
else
echo "Not running for PR"
fi
yarn testsafari --forceExit test/integration/production/
environment:
NEXT_TELEMETRY_DISABLED: '1'
BROWSERSTACK: 'true'
BROWSER_NAME: << parameters.browser >>
test_firefox:
steps:
- run:
name: Test Firefox
command: |
yarn testfirefox --forceExit test/integration/production/
environment:
NEXT_TELEMETRY_DISABLED: '1'
save_npm_token:
steps:
......@@ -151,24 +147,16 @@ jobs:
- yarn_info
- test_all
- *store_test_results
test-ie11:
executor: node
steps:
- *attach_workspace
- test_browser:
browser: 'ie'
test-safari:
executor: node
steps:
- *attach_workspace
- test_browser:
browser: 'safari'
- test_safari
test-firefox:
executor: node
steps:
- *attach_workspace
- test_browser:
browser: 'firefox'
- test_firefox
deploy:
executor: node
steps:
......@@ -186,41 +174,23 @@ workflows:
build-test-and-deploy:
jobs:
- build
- test:
requires:
- build
- lint:
- test-firefox:
requires:
- build
- test-ie11:
- test:
requires:
- build
filters:
branches:
only:
- master
- canary
- test-safari:
requires:
- build
- test
- test-ie11
filters:
branches:
only:
- master
- canary
- test-firefox:
- lint:
requires:
- build
- test
- test-ie11
- test-safari
filters:
branches:
only:
- master
- canary
- deploy:
requires:
- test
......
pool:
vmImage: 'windows-2019'
variables:
NEXT_TELEMETRY_DISABLED: '1'
YARN_CACHE_FOLDER: $(Pipeline.Workspace)/.yarn
CHROMEDRIVER_VERSION: '78.0.3904.70'
strategy:
maxParallel: 10
matrix:
node-10-1:
group: 1/4
node_version: ^10.10.0
node-10-2:
group: 2/4
node_version: ^10.10.0
node-10-3:
group: 3/4
node_version: ^10.10.0
node-10-4:
group: 4/4
node_version: ^10.10.0
steps:
- script: |
wmic datafile where name="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" get Version /value
displayName: 'List Chrome version'
- task: NodeTool@0
inputs:
versionSpec: $(node_version)
displayName: 'Install Node.js'
- task: CacheBeta@0
inputs:
key: yarn | $(Agent.OS) | yarn.lock
path: $(YARN_CACHE_FOLDER)
displayName: Cache Yarn packages
- script: |
yarn install --frozen-lockfile --check-files
displayName: 'Install dependencies'
- script: |
node node_modules/chromedriver/install.js
displayName: 'Install correct Chrome Driver version'
- script: |
node run-tests.js -g $(group)
displayName: 'Run tests'
NEXT_TELEMETRY_DISABLED: '1'
node_version: ^10.10.0
jobs:
- job: test_ie11
pool:
vmImage: 'windows-2019'
steps:
- task: NodeTool@0
inputs:
versionSpec: $(node_version)
displayName: 'Install Node.js'
- task: CacheBeta@0
inputs:
key: yarn | $(Agent.OS) | yarn.lock
path: $(YARN_CACHE_FOLDER)
displayName: Cache Yarn packages
- script: |
yarn install --frozen-lockfile --check-files
displayName: 'Install dependencies'
- script: |
yarn testie --forceExit test/integration/production/
displayName: 'Run tests'
- job: test_chrome
pool:
vmImage: 'windows-2019'
strategy:
maxParallel: 10
matrix:
node-10-1:
group: 1/4
node-10-2:
group: 2/4
node-10-3:
group: 3/4
node-10-4:
group: 4/4
steps:
- script: |
wmic datafile where name="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" get Version /value
displayName: 'List Chrome version'
- task: NodeTool@0
inputs:
versionSpec: $(node_version)
displayName: 'Install Node.js'
- task: CacheBeta@0
inputs:
key: yarn | $(Agent.OS) | yarn.lock
path: $(YARN_CACHE_FOLDER)
displayName: Cache Yarn packages
- script: |
yarn install --frozen-lockfile --check-files
displayName: 'Install dependencies'
- script: |
node run-tests.js -g $(group)
displayName: 'Run tests'
......@@ -9,7 +9,10 @@
"dev": "lerna run build --stream --parallel",
"dev2": "while true; do yarn --check-files && yarn dev; done",
"testonly": "jest --runInBand",
"testheadless": "HEADLESS=true yarn testonly",
"testheadless": "cross-env HEADLESS=true yarn testonly",
"testsafari": "cross-env BROWSER_NAME=safari yarn testonly",
"testfirefox": "cross-env BROWSER_NAME=firefox yarn testonly",
"testie": "cross-env BROWSER_NAME=\"internet explorer\" yarn testonly",
"testall": "yarn run testonly -- --ci --forceExit",
"pretest": "yarn run lint",
"git-reset": "git reset --hard HEAD",
......@@ -52,9 +55,9 @@
"babel-jest": "24.9.0",
"browserstack-local": "1.4.0",
"cheerio": "0.22.0",
"chromedriver": "78.0.1",
"clone": "2.1.2",
"coveralls": "3.0.3",
"cross-env": "6.0.3",
"cross-spawn": "6.0.5",
"escape-string-regexp": "2.0.0",
"eslint": "6.6.0",
......@@ -89,13 +92,14 @@
"release": "6.0.1",
"request-promise-core": "1.1.2",
"rimraf": "2.6.3",
"selenium-standalone": "6.17.0",
"selenium-webdriver": "4.0.0-alpha.5",
"shell-quote": "1.7.2",
"tailwindcss": "1.1.3",
"taskr": "1.1.0",
"tree-kill": "1.2.1",
"typescript": "3.7.3",
"wait-port": "0.2.2",
"wd": "1.11.3",
"webpack-bundle-analyzer": "3.3.2"
},
"resolutions": {
......
......@@ -82,7 +82,7 @@ describe('Client Navigation', () => {
await waitFor(3000)
await browser.back()
await waitFor(3000)
const text = await browser.elementsByCss('#about-link').text()
const text = await browser.elementByCss('#about-link').text()
if (browser) await browser.close()
expect(text).toMatch(/About/)
})
......@@ -96,7 +96,7 @@ describe('Client Navigation', () => {
await waitFor(3000)
await browser.forward()
await waitFor(3000)
const text = await browser.elementsByCss('p').text()
const text = await browser.elementByCss('p').text()
if (browser) await browser.close()
expect(text).toMatch(/this is the about page/i)
})
......
......@@ -266,7 +266,7 @@ const runTests = (dev = false) => {
const browser = await webdriver(appPort, '/')
await waitFor(500)
await browser.eval('window.beforeClick = true')
await browser.click('#broken-post')
await browser.elementByCss('#broken-post').click()
await waitFor(1000)
expect(await browser.eval('window.beforeClick')).not.toBe('true')
})
......
......@@ -6,22 +6,22 @@ export default () => {
<ul>
<li>
<Link href="/" prefetch>
<a>index</a>
<a id="prefetch-1">index</a>
</Link>
</li>
<li>
<Link href="/process-env" prefetch>
<a>process env</a>
<a id="prefetch-2">process env</a>
</Link>
</li>
<li>
<Link href="/counter" prefetch>
<a>counter</a>
<a id="prefetch-3">counter</a>
</Link>
</li>
<li>
<Link href="/about" prefetch>
<a>about</a>
<a id="prefetch-4">about</a>
</Link>
</li>
</ul>
......
......@@ -441,45 +441,60 @@ describe('Production Usage', () => {
}
})
if (browserName === 'chrome') {
it('should add prefetch tags when Link prefetch prop is used', async () => {
const browser = await webdriver(appPort, '/prefetch')
await waitFor(2000)
const elements = await browser.elementsByCss('link[rel=prefetch]')
it('should add prefetch tags when Link prefetch prop is used', async () => {
const browser = await webdriver(appPort, '/prefetch')
if (browserName === 'internet explorer') {
// IntersectionObserver isn't present so we need to trigger manually
await waitFor(1000)
await browser.eval(`(function() {
window.next.router.prefetch('/')
window.next.router.prefetch('/process-env')
window.next.router.prefetch('/counter')
window.next.router.prefetch('/about')
})()`)
}
await waitFor(2000)
if (browserName === 'safari') {
const elements = await browser.elementsByCss('link[rel=preload]')
// 4 page preloads and 5 existing preloads for _app, commons, main, etc
expect(elements.length).toBe(9)
} else {
const elements = await browser.elementsByCss('link[rel=prefetch]')
expect(elements.length).toBe(4)
await Promise.all(
elements.map(async element => {
const rel = await element.getAttribute('rel')
const as = await element.getAttribute('as')
expect(rel).toBe('prefetch')
expect(as).toBe('script')
})
)
await browser.close()
})
// This is a workaround to fix https://github.com/zeit/next.js/issues/5860
// TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed.
it('It does not add a timestamp to link tags with prefetch attribute', async () => {
const browser = await webdriver(appPort, '/prefetch')
const links = await browser.elementsByCss('link[rel=prefetch]')
await Promise.all(
links.map(async element => {
const href = await element.getAttribute('href')
expect(href).not.toMatch(/\?ts=/)
})
)
const scripts = await browser.elementsByCss('script[src]')
await Promise.all(
scripts.map(async element => {
const src = await element.getAttribute('src')
expect(src).not.toMatch(/\?ts=/)
})
)
await browser.close()
})
for (const element of elements) {
const rel = await element.getAttribute('rel')
const as = await element.getAttribute('as')
expect(rel).toBe('prefetch')
expect(as).toBe('script')
}
}
await browser.close()
})
// This is a workaround to fix https://github.com/zeit/next.js/issues/5860
// TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed.
it('It does not add a timestamp to link tags with prefetch attribute', async () => {
const browser = await webdriver(appPort, '/prefetch')
const links = await browser.elementsByCss('link[rel=prefetch]')
for (const element of links) {
const href = await element.getAttribute('href')
expect(href).not.toMatch(/\?ts=/)
}
const scripts = await browser.elementsByCss('script[src]')
for (const element of scripts) {
const src = await element.getAttribute('src')
expect(src).not.toMatch(/\?ts=/)
}
await browser.close()
})
if (browserName === 'chrome') {
it('should reload the page on page script error with prefetch', async () => {
const browser = await webdriver(appPort, '/counter')
if (global.browserName !== 'chrome') return
......
// my-custom-environment
const wd = require('wd')
const os = require('os')
const http = require('http')
const fetch = require('node-fetch')
const getPort = require('get-port')
const waitPort = require('wait-port')
const chromedriver = require('chromedriver')
const seleniumServer = require('selenium-standalone')
const NodeEnvironment = require('jest-environment-node')
const {
BROWSER_NAME,
BROWSERSTACK,
BROWSERSTACK_USERNAME,
BROWSERSTACK_ACCESS_KEY,
} = process.env
let browser
let initialWindow
let browserOptions = {
browserName: BROWSER_NAME || 'chrome',
...(process.env.HEADLESS === 'true'
? {
chromeOptions: { args: ['--headless'] },
}
: {}),
}
let deviceIP = 'localhost'
let driverPort = '9515'
const isIE = BROWSER_NAME === 'ie'
const isSafari = BROWSER_NAME === 'safari'
const isFirefox = BROWSER_NAME === 'firefox'
// 30 seconds for BrowserStack 5 seconds for local
const isBrowserStack =
BROWSERSTACK && BROWSERSTACK_USERNAME && BROWSERSTACK_ACCESS_KEY
const browserTimeout = (isBrowserStack ? 30 : 5) * 1000
if (isBrowserStack) {
const safariOpts = {
os: 'OS X',
os_version: 'Mojave',
browser: 'Safari',
}
const ieOpts = {
os: 'Windows',
os_version: '10',
browser: 'IE',
}
const firefoxOpts = {
os: 'Windows',
os_version: '10',
browser: 'Firefox',
}
const sharedOpts = {
'browserstack.local': true,
'browserstack.video': false,
'browserstack.localIdentifier':
global.browserStackLocal.localIdentifierFlag,
}
browserOptions = {
...browserOptions,
...sharedOpts,
...(isIE ? ieOpts : {}),
...(isSafari ? safariOpts : {}),
...(isFirefox ? firefoxOpts : {}),
}
}
const { BROWSER_NAME: browserName = 'chrome' } = process.env
const newTabPg = `
<!DOCTYPE html>
......@@ -81,160 +19,66 @@ const newTabPg = `
`
class CustomEnvironment extends NodeEnvironment {
async createBrowser() {
// always create new browser session if not BrowserStack
if (!browser) {
if (!isBrowserStack) {
driverPort = await getPort()
chromedriver.start([`--port=${driverPort}`])
// https://github.com/giggio/node-chromedriver/issues/117
await waitPort({
port: driverPort,
timeout: 1000 * 60 * 2, // 2 Minutes
})
}
browser = wd.promiseChainRemote(
...(isBrowserStack
? [
'hub-cloud.browserstack.com', // seleniumHost
80, // seleniumPort
BROWSERSTACK_USERNAME,
BROWSERSTACK_ACCESS_KEY,
]
: [`http://localhost:${driverPort}`])
)
// Setup the browser instance
await browser.init(browserOptions)
initialWindow = await browser.windowHandle()
}
// disable browser.close and we handle it manually
browser.origClose = browser.close
browser.close = () => {}
async setup() {
await super.setup()
// Since ie11 doesn't like dataURIs we have to spin up a
// server to handle the new tab page
this.server = http.createServer((req, res) => {
res.statusCode = 200
res.end(newTabPg)
})
this.newTabPort = await getPort()
const newTabPort = await getPort()
await new Promise((resolve, reject) => {
this.server.listen(this.newTabPort, err => {
this.server.listen(newTabPort, err => {
if (err) return reject(err)
resolve()
})
})
if (isBrowserStack) {
const networkIntfs = os.networkInterfaces()
// find deviceIP to use with BrowserStack
for (const intf of Object.keys(networkIntfs)) {
const addresses = networkIntfs[intf]
let seleniumServerPort
for (const { internal, address, family } of addresses) {
if (family !== 'IPv4' || internal) continue
try {
const res = await fetch(`http://${address}:${this.newTabPort}`)
if (res.ok) {
deviceIP = address
break
}
} catch (_) {}
}
}
}
this.global.browserName = browserOptions.browserName
// Mock current browser set up
this.global.sharedWD = async (appPort, pathname) => {
const url = `http://${deviceIP}:${appPort}${pathname}`
console.log(`\n> Loading browser with ${url}\n`)
await this.freshWindow()
return new Promise((resolve, reject) => {
let timedOut = false
const timeoutHandler = setTimeout(() => {
timedOut = true
reject(new Error(`Loading browser with ${url} timed out`))
}, browserTimeout)
browser.get(url, err => {
if (browserName !== 'chrome') {
console.log('Installing selenium server')
await new Promise((resolve, reject) => {
seleniumServer.install(err => {
if (err) return reject(err)
clearTimeout(timeoutHandler)
if (!timedOut) resolve(browser)
resolve()
})
})
}
}
async freshWindow(tries = 0) {
if (tries > 3) throw new Error('failed to get fresh browser window')
// Since we need a fresh start for each window
// we have to force a new tab which can be disposed
const startWindows = await browser.windowHandles()
// let's close all windows that aren't the initial window
for (const window of startWindows) {
if (!window || window === initialWindow) continue
try {
await browser.window(window)
await browser.origClose()
} catch (_) {
/* should already be closed */
}
}
// focus initial window
await browser.window(initialWindow)
const newTabUrl = `http://${deviceIP}:${this.newTabPort}/`
// load html to open new tab
if ((await browser.url()) !== newTabUrl) {
await browser.get(newTabUrl)
}
// click new tab link
await browser.elementByCss('#new').click()
// focus fresh window
const newWindows = await browser.windowHandles()
try {
await browser.window(
newWindows.find(win => {
if (win && win !== initialWindow && startWindows.indexOf(win) < 0) {
return win
}
return false
console.log('Starting selenium server')
await new Promise((resolve, reject) => {
seleniumServer.start((err, child) => {
if (err) return reject(err)
this.seleniumServer = child
resolve()
})
)
} catch (err) {
await this.freshWindow(tries + 1)
})
console.log('Started selenium server')
seleniumServerPort = 4444
}
}
async setup() {
await super.setup()
await this.createBrowser()
this.global.wd = null
this.global._newTabPort = newTabPort
this.global.browserName = browserName
this.global.seleniumServerPort = seleniumServerPort
this.global.browserStackLocalId = global.browserStackLocalId
}
async teardown() {
await super.teardown()
if (this.server) this.server.close()
if (browser) {
// Close all remaining browser windows
try {
const windows = await browser.windowHandles()
for (const window of windows) {
if (!window) continue
await browser.window(window)
await browser.origClose()
await browser.quit()
}
} catch (_) {}
if (this.server) {
this.server.close()
}
if (this.global.wd) {
await this.global.wd.quit()
}
// must come after wd.quit()
if (this.seleniumServer) {
this.seleniumServer.kill()
}
chromedriver.stop()
}
}
......
......@@ -8,6 +8,7 @@ if (process.env.BROWSERSTACK) {
localIdentifier: new Date().getTime(), // Adding a unique local identifier to run parallel tests on BrowserStack
}
global.browserStackLocal = browserStackLocal
global.browserStackLocalId = localBrowserStackOpts.localIdentifier
globalSetup = () => {
return new Promise((resolve, reject) => {
......
export default global.sharedWD
import os from 'os'
import path from 'path'
import fetch from 'node-fetch'
import { until, Builder, By } from 'selenium-webdriver'
import { Options as ChromeOptions } from 'selenium-webdriver/chrome'
import { Options as SafariOptions } from 'selenium-webdriver/safari'
import { Options as FireFoxOptions } from 'selenium-webdriver/firefox'
const {
BROWSER_NAME: browserName = 'chrome',
BROWSERSTACK,
BROWSERSTACK_USERNAME,
BROWSERSTACK_ACCESS_KEY,
HEADLESS,
CHROME_BIN,
} = process.env
let capabilities = {}
const isChrome = browserName === 'chrome'
const isSafari = browserName === 'safari'
const isFirefox = browserName === 'firefox'
const isIE = browserName === 'internet explorer'
if (process.env.ChromeWebDriver) {
process.env.PATH = `${process.env.ChromeWebDriver}${path.delimiter}${process.env.PATH}`
}
const isBrowserStack =
BROWSERSTACK && BROWSERSTACK_USERNAME && BROWSERSTACK_ACCESS_KEY
if (isBrowserStack) {
const safariOpts = {
os: 'OS X',
os_version: 'Mojave',
browser: 'Safari',
}
const ieOpts = {
os: 'Windows',
os_version: '10',
browser: 'IE',
}
const firefoxOpts = {
os: 'Windows',
os_version: '10',
browser: 'Firefox',
}
const sharedOpts = {
'browserstack.local': true,
'browserstack.video': false,
'browserstack.user': BROWSERSTACK_USERNAME,
'browserstack.key': BROWSERSTACK_ACCESS_KEY,
'browserstack.localIdentifier': global.browserStackLocalId,
}
capabilities = {
...capabilities,
...sharedOpts,
...(isIE ? ieOpts : {}),
...(isSafari ? safariOpts : {}),
...(isFirefox ? firefoxOpts : {}),
}
}
let chromeOptions = new ChromeOptions()
let firefoxOptions = new FireFoxOptions()
let safariOptions = new SafariOptions()
if (HEADLESS) {
const screenSize = { width: 1280, height: 720 }
chromeOptions = chromeOptions.headless().windowSize(screenSize)
firefoxOptions = firefoxOptions.headless().windowSize(screenSize)
}
if (CHROME_BIN) {
chromeOptions = chromeOptions.setChromeBinaryPath(path.resolve(CHROME_BIN))
}
let seleniumServer
if (isBrowserStack) {
seleniumServer = 'http://hub-cloud.browserstack.com/wd/hub'
} else if (global.seleniumServerPort) {
seleniumServer = `http://localhost:${global.seleniumServerPort}/wd/hub`
}
let browser = new Builder()
.usingServer(seleniumServer)
.withCapabilities(capabilities)
.forBrowser(browserName)
.setChromeOptions(chromeOptions)
.setFirefoxOptions(firefoxOptions)
.setSafariOptions(safariOptions)
.build()
global.wd = browser
/*
# Methods to match
- elementByCss
- elementsByCss
- waitForElementByCss
- elementByCss.text
- elementByCss.click
*/
let initialWindow
let deviceIP = 'localhost'
const getDeviceIP = async () => {
const networkIntfs = os.networkInterfaces()
// find deviceIP to use with BrowserStack
for (const intf of Object.keys(networkIntfs)) {
const addresses = networkIntfs[intf]
for (const { internal, address, family } of addresses) {
if (family !== 'IPv4' || internal) continue
try {
const res = await fetch(`http://${address}:${global._newTabPort}`)
if (res.ok) {
deviceIP = address
break
}
} catch (_) {}
}
}
}
// eslint-disable-next-line no-unused-vars
const freshWindow = async () => {
// First we close all extra windows left over
let allWindows = await browser.getAllWindowHandles()
for (const win of allWindows) {
if (win === initialWindow) continue
try {
await browser.switchTo().window(win)
await browser.close()
} catch (_) {}
}
await browser.switchTo().window(initialWindow)
// now we open a fresh window
await browser.get(`http://${deviceIP}:${global._newTabPort}`)
const newTabLink = await browser.findElement(By.css('#new'))
await newTabLink.click()
allWindows = await browser.getAllWindowHandles()
const newWindow = allWindows.find(win => win !== initialWindow)
await browser.switchTo().window(newWindow)
}
export default async (appPort, path) => {
if (!initialWindow) {
initialWindow = await browser.getWindowHandle()
}
if (isBrowserStack && deviceIP === 'localhost') {
await getDeviceIP()
}
// browser.switchTo().window() fails with `missing field `handle``
// in safari and firefox so disabling freshWindow since our
// tests shouldn't rely on it
if (isChrome) {
await freshWindow()
}
const url = `http://${deviceIP}:${appPort}${path}`
console.log(`\n> Loading browser with ${url}\n`)
await browser.get(url)
console.log(`\n> Loaded browser with ${url}\n`)
class Chain {
updateChain(nextCall) {
if (!this.promise) {
this.promise = Promise.resolve()
}
this.promise = this.promise.then(nextCall)
this.then = cb => this.promise.then(cb)
this.catch = cb => this.promise.catch(cb)
this.finally = cb => this.promise.finally(cb)
return this
}
elementByCss(sel) {
return this.updateChain(() =>
browser.findElement(By.css(sel)).then(el => {
el.sel = sel
el.text = () => el.getText()
el.getComputedCss = prop => el.getCssValue(prop)
el.type = text => el.sendKeys(text)
el.getValue = () =>
browser.executeScript(
`return document.querySelector('${sel}').value`
)
return el
})
)
}
elementById(sel) {
return this.elementByCss(`#${sel}`)
}
getValue() {
return this.updateChain(el =>
browser.executeScript(
`return document.querySelector('${el.sel}').value`
)
)
}
text() {
return this.updateChain(el => el.getText())
}
type(text) {
return this.updateChain(el => el.sendKeys(text))
}
moveTo() {
return this.updateChain(el => {
return browser
.actions()
.move({ origin: el })
.perform()
.then(() => el)
})
}
getComputedCss(prop) {
return this.updateChain(el => {
return el.getCssValue(prop)
})
}
getAttribute(attr) {
return this.updateChain(el => el.getAttribute(attr))
}
hasElementByCssSelector(sel) {
return this.eval(`document.querySelector('${sel}')`)
}
click() {
return this.updateChain(el => {
return el.click().then(() => el)
})
}
elementsByCss(sel) {
return this.updateChain(() => browser.findElements(By.css(sel)))
}
waitForElementByCss(sel, timeout) {
return this.updateChain(() =>
browser.wait(until.elementLocated(By.css(sel), timeout))
)
}
eval(snippet) {
if (typeof snippet === 'string' && !snippet.startsWith('return')) {
snippet = `return ${snippet}`
}
return this.updateChain(() => browser.executeScript(snippet))
}
log(type) {
return this.updateChain(() =>
browser
.manage()
.logs()
.get(type)
)
}
url() {
return this.updateChain(() => browser.getCurrentUrl())
}
back() {
return this.updateChain(() => browser.navigate().back())
}
forward() {
return this.updateChain(() => browser.navigate().forward())
}
refresh() {
return this.updateChain(() => browser.navigate().refresh())
}
close() {
return this.updateChain(() => Promise.resolve())
}
quit() {
return this.close()
}
}
const promiseProp = new Set(['then', 'catch', 'finally'])
return new Proxy(new Chain(), {
get(obj, prop) {
if (obj[prop] || promiseProp.has(prop)) {
return obj[prop]
}
return browser[prop]
},
})
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment