diff --git a/packages/expect-puppeteer/src/matchers/toFill.js b/packages/expect-puppeteer/src/matchers/toFill.js index 0ea8cb53..9105b4c2 100644 --- a/packages/expect-puppeteer/src/matchers/toFill.js +++ b/packages/expect-puppeteer/src/matchers/toFill.js @@ -1,5 +1,29 @@ 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( @@ -7,7 +31,7 @@ async function toFill(instance, selector, value, options) { selector, toMatchElementOptions, ) - await element.click({ clickCount: 3 }) + await selectAll(element) await element.press('Backspace') await element.type(value, { delay, diff --git a/packages/expect-puppeteer/src/matchers/toFill.test.js b/packages/expect-puppeteer/src/matchers/toFill.test.js index 6887df54..de3aae0c 100644 --- a/packages/expect-puppeteer/src/matchers/toFill.test.js +++ b/packages/expect-puppeteer/src/matchers/toFill.test.js @@ -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) diff --git a/server/public/index.html b/server/public/index.html index 7cd6b65f..dee63720 100644 --- a/server/public/index.html +++ b/server/public/index.html @@ -23,6 +23,7 @@
+
@@ -37,4 +38,4 @@
- \ No newline at end of file +