Skip to content

Commit

Permalink
fix: fix toFill on textarea (#399)
Browse files Browse the repository at this point in the history
  • Loading branch information
UziTech authored Apr 22, 2021
1 parent 07e0e4f commit 7f40bd7
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
26 changes: 25 additions & 1 deletion packages/expect-puppeteer/src/matchers/toFill.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
import toMatchElement from './toMatchElement'

async function selectAll(element) {
// modified from https://github.com/microsoft/playwright/issues/849#issuecomment-587983363
await element.evaluate((elementHandle) => {
if (elementHandle.setSelectionRange) {
try {
elementHandle.setSelectionRange(0, elementHandle.value.length)
} catch (e) {
// setSelectionRange throws an error for inputs: number/date/time/etc
// we can just focus them and the content will be selected
elementHandle.focus()
}
} else if (window.getSelection && document.createRange) {
const range = document.createRange()
range.selectNodeContents(elementHandle)

const selection = window.getSelection()
if (selection) {
selection.removeAllRanges()
selection.addRange(range)
}
}
})
}

async function toFill(instance, selector, value, options) {
const { delay, ...toMatchElementOptions } = options || {}
const element = await toMatchElement(
instance,
selector,
toMatchElementOptions,
)
await element.click({ clickCount: 3 })
await selectAll(element)
await element.press('Backspace')
await element.type(value, {
delay,
Expand Down
23 changes: 23 additions & 0 deletions packages/expect-puppeteer/src/matchers/toFill.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,29 @@ describe('toFill', () => {
expect(value).toBe('')
})

fit('should fill textarea', async () => {
await expect(page).toFill(
'[name="notes"]',
'These are \n multiline \n notes',
)
const value = await page.evaluate(
() => document.querySelector('[name="notes"]').value,
)
expect(value).toBe('These are \n multiline \n notes')
})

fit('should empty the textarea given an empty string', async () => {
await expect(page).toFill(
'[name="notes"]',
'These are \n multiline \n notes',
)
await expect(page).toFill('[name="notes"]', '')
const value = await page.evaluate(
() => document.querySelector('[name="notes"]').value,
)
expect(value).toBe('')
})

it('should return an error if text is not in the page', async () => {
expect.assertions(2)

Expand Down
3 changes: 2 additions & 1 deletion server/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
<form>
<input name="firstName" />
<input name="lastName" />
<textarea name="notes"></textarea>
</form>
<button id="dialog-btn" onclick="window.confirm('Bouh!')">Open dialog</button>
<main>
Expand All @@ -37,4 +38,4 @@
</main>
</body>

</html>
</html>

0 comments on commit 7f40bd7

Please sign in to comment.