Skip to content

Commit

Permalink
Merge pull request #221 from testing-library/fix-type-with-text
Browse files Browse the repository at this point in the history
fix: 🐛 type supports fields with previous text
  • Loading branch information
Gpx committed Feb 17, 2020
2 parents 9d50ff6 + f1283f6 commit 34c9d41
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 @@ -185,11 +185,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 @@ -211,7 +215,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 34c9d41

Please sign in to comment.