Skip to content

Commit

Permalink
Allow fillIn to trigger keyup, keypress and keyup events as well
Browse files Browse the repository at this point in the history
  • Loading branch information
mfeckie committed Jul 14, 2018
1 parent a4253d1 commit 3e32044
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
34 changes: 33 additions & 1 deletion addon-test-support/@ember/test-helpers/dom/fill-in.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import { nextTickPromise } from '../-utils';
@public
@param {string|Element} target the element or selector to enter text into
@param {string} text the text to fill into the target element
@param {boolean} withKeyEvents trigger keyDown, keyPress and keyUp for each character in the text
@return {Promise<void>} resolves when the application is settled
*/
export default function fillIn(target, text) {
export default function fillIn(target, text, withKeyEvents = false) {
return nextTickPromise().then(() => {
if (!target) {
throw new Error('Must pass an element or selector to `fillIn`.');
Expand All @@ -37,6 +38,9 @@ export default function fillIn(target, text) {
__focus__(element);

if (isControl) {
if (withKeyEvents) {
fillInWithKeyEvents(element, text);
}
element.value = text;
} else {
element.innerHTML = text;
Expand All @@ -48,3 +52,31 @@ export default function fillIn(target, text) {
return settled();
});
}

// eslint-disable-next-line require-jsdoc
function fillInWithKeyEvents(element, text) {
const keyboardEvents = text.split().map(charCode => keyEvents(charCode));

keyboardEvents.forEach(events => {
element.dispatchEvent(events.keyDown);
element.dispatchEvent(events.keyPress);
element.dispatchEvent(events.keyUp);
});
}

// eslint-disable-next-line require-jsdoc
function keyEvents(character) {
const charCode = character.charCodeAt();

const eventOptions = {
bubbles: true,
cancelable: true,
charCode,
};

return {
keyDown: new KeyboardEvent('keydown', eventOptions),
keyPress: new KeyboardEvent('keypress', eventOptions),
keyUp: new KeyboardEvent('keyup', eventOptions),
};
}
13 changes: 13 additions & 0 deletions tests/unit/dom/fill-in-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,17 @@ module('DOM Helper: fillIn', function(hooks) {
assert.strictEqual(document.activeElement, element, 'activeElement updated');
assert.equal(element.value, '');
});

test('filling an input with keyboard events', async function(assert) {
element = buildInstrumentedElement('input');

await setupContext(context);
await fillIn(element, 'foo', true);

const expectedSteps = ['focus', 'focusin', 'keydown', 'keypress', 'keyup', 'input', 'change'];

assert.verifySteps(expectedSteps);
assert.strictEqual(document.activeElement, element, 'activeElement updated');
assert.equal(element.value, 'foo');
});
});

0 comments on commit 3e32044

Please sign in to comment.