Skip to content

Commit

Permalink
fix: 🐛 type supports fields with previous text
Browse files Browse the repository at this point in the history
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
  • Loading branch information
Gpx committed Feb 17, 2020
1 parent 61398ad commit 1e8d140
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
22 changes: 22 additions & 0 deletions __tests__/react/type.js
Expand Up @@ -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(
<input data-testid="input" onChange={onChange} />
);
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(
<input data-testid="input" onChange={onChange} />
);
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
Expand Down
10 changes: 7 additions & 3 deletions src/index.js
Expand Up @@ -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
Expand All @@ -222,7 +226,7 @@ const userEvent = {
});

const isTextPastThreshold =
(actuallyTyped + key).length > computedText.length;
(actuallyTyped + key).length > (previousText + computedText).length;

if (pressEvent && !isTextPastThreshold) {
actuallyTyped += key;
Expand Down

0 comments on commit 1e8d140

Please sign in to comment.