From 1e8d140b0e67aa9da089c832deb997c2a15d5a33 Mon Sep 17 00:00:00 2001 From: Gpx Date: Mon, 17 Feb 2020 11:43:58 +0100 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=90=9B=20type=20supports=20fields?= =?UTF-8?q?=20with=20previous=20text?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When using .type() with an input field that had already text inside the new text is added to the field BREAKING CHANGE: 🧨 Using .type() with an input field that had text already inside preserve the exisiting value and appends the typed text --- __tests__/react/type.js | 22 ++++++++++++++++++++++ src/index.js | 10 +++++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/__tests__/react/type.js b/__tests__/react/type.js index f2b61552..ca804e9b 100644 --- a/__tests__/react/type.js +++ b/__tests__/react/type.js @@ -20,6 +20,28 @@ describe("userEvent.type", () => { expect(getByTestId("input")).toHaveProperty("value", text); }); + it("should append text one by one", () => { + const onChange = jest.fn(); + const { getByTestId } = render( + + ); + userEvent.type(getByTestId("input"), "hello"); + userEvent.type(getByTestId("input"), " world"); + expect(onChange).toHaveBeenCalledTimes("hello world".length); + expect(getByTestId("input")).toHaveProperty("value", "hello world"); + }); + + it("should append text all at once", () => { + const onChange = jest.fn(); + const { getByTestId } = render( + + ); + userEvent.type(getByTestId("input"), "hello", { allAtOnce: true }); + userEvent.type(getByTestId("input"), " world", { allAtOnce: true }); + expect(onChange).toHaveBeenCalledTimes(2); + expect(getByTestId("input")).toHaveProperty("value", "hello world"); + }); + it("should not type when event.preventDefault() is called", () => { const onChange = jest.fn(); const onKeydown = jest diff --git a/src/index.js b/src/index.js index c6637987..486d7695 100644 --- a/src/index.js +++ b/src/index.js @@ -196,11 +196,15 @@ const userEvent = { const computedText = text.slice(0, element.maxLength || text.length); + const previousText = element.value; + if (opts.allAtOnce) { if (element.readOnly) return; - fireEvent.input(element, { target: { value: computedText } }); + fireEvent.input(element, { + target: { value: previousText + computedText } + }); } else { - let actuallyTyped = ""; + let actuallyTyped = previousText; for (let index = 0; index < text.length; index++) { const char = text[index]; const key = char; // TODO: check if this also valid for characters with diacritic markers e.g. úé etc @@ -222,7 +226,7 @@ const userEvent = { }); const isTextPastThreshold = - (actuallyTyped + key).length > computedText.length; + (actuallyTyped + key).length > (previousText + computedText).length; if (pressEvent && !isTextPastThreshold) { actuallyTyped += key;