Skip to content

Commit 5fbbbad

Browse files
committed
fix: Respect maxLength prop in type() function
This commit modifies the `type()` function to respect the `maxLength` prop of the input element. If the current text length exceeds the `maxLength` value, typing events will not be emitted. This ensures that the input value does not exceed the specified maximum length. 1. Create an input element with a `maxLength` prop. 2. Use the `type()` function to input text that exceeds the `maxLength` value. 3. Verify that the input value does not exceed the specified maximum length. 4. Check that no typing events are emitted once the `maxLength` is reached. Additionally, see that `yarn test` passes with an additional test added to `src/user-event/type/__tests__/type.test.tsx`
1 parent 6cc4c0c commit 5fbbbad

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/user-event/type/__tests__/type.test.tsx

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,4 +338,36 @@ describe('type()', () => {
338338
await userEvent.type(screen.getByTestId('input'), 'abc');
339339
expect(handleKeyPress).toHaveBeenCalledTimes(3);
340340
});
341+
342+
it('does respect maxLength prop', async () => {
343+
const { events, ...queries } = renderTextInputWithToolkit({
344+
maxLength: 2,
345+
});
346+
347+
const user = userEvent.setup();
348+
await user.type(queries.getByTestId('input'), 'abc');
349+
350+
const eventNames = events.map((e) => e.name);
351+
expect(eventNames).toEqual([
352+
'pressIn',
353+
'focus',
354+
'pressOut',
355+
'keyPress',
356+
'change',
357+
'changeText',
358+
'selectionChange',
359+
'keyPress',
360+
'change',
361+
'changeText',
362+
'selectionChange',
363+
'endEditing',
364+
'blur',
365+
]);
366+
367+
const lastChangeTestEvent = events.filter((e) => e.name === 'changeText').pop();
368+
expect(lastChangeTestEvent).toMatchObject({
369+
name: 'changeText',
370+
payload: 'ab',
371+
});
372+
});
341373
});

src/user-event/type/type.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ export async function type(
4949
const previousText = element.props.value ?? currentText;
5050
currentText = applyKey(previousText, key);
5151

52-
await emitTypingEvents(this.config, element, key, currentText, previousText);
52+
if (element.props.maxLength === undefined || currentText.length <= element.props.maxLength) {
53+
await emitTypingEvents(this.config, element, key, currentText, previousText);
54+
}
5355
}
5456

5557
const finalText = element.props.value ?? currentText;

0 commit comments

Comments
 (0)