Skip to content
This repository has been archived by the owner on Jul 8, 2023. It is now read-only.

Commit

Permalink
➕ page: add focus() (close #17)
Browse files Browse the repository at this point in the history
  • Loading branch information
deepsweet committed Aug 23, 2018
1 parent 337c610 commit e0c5a68
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/api/Page.ts
Expand Up @@ -137,6 +137,23 @@ class Page extends EventEmitter {
return result.value
}

async focus (selector: string) {
/* istanbul ignore next */
return this.evaluate((sel) => {
const el = document.querySelector(sel as string)

if (el === null) {
throw new Error('Unable to find element')
}

if (!(el instanceof HTMLElement)) {
throw new Error('Found element is not HTMLElement and not focusable')
}

el.focus()
}, selector)
}

async goto (url: string) {
await this._send('WebDriver:Navigate', { url })
}
Expand Down
40 changes: 40 additions & 0 deletions test/api/Page.ts
Expand Up @@ -209,6 +209,46 @@ test('Page: `evaluate()`', testWithFirefox(async (t) => {
}
}))

test('Page: `focus()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()

await page.setContent('<div><input/><svg></svg></div>')

const activeElementBefore = await page.evaluate('document.activeElement.tagName')

await page.focus('input')

const activeElementAfter = await page.evaluate('document.activeElement.tagName')

t.true(
activeElementBefore !== activeElementAfter && activeElementAfter === 'INPUT',
'should focus element'
)

try {
await page.focus('foo')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: Unable to find element',
'should throw if there is no such an element'
)
}

try {
await page.focus('svg')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: Found element is not HTMLElement and not focusable',
'should throw if found element is not focusable'
)
}
}))

test('Page: `goto()` + `url()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Expand Up @@ -4,7 +4,7 @@
"allowSyntheticDefaultImports": true,
"noEmit": true,
"pretty": true,
"lib": ["esnext"],
"lib": ["esnext", "dom"],
"moduleResolution": "node",
"typeRoots": [ "types/", "node_modules/@types/" ]
},
Expand Down

0 comments on commit e0c5a68

Please sign in to comment.