Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sarayourfriend committed Jul 7, 2021
1 parent 0067489 commit 7fd294c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/components/src/utils/keyboard.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
/**
* WordPress dependencies
*/
import { RIGHT, UP, DOWN, LEFT } from '@wordpress/keycodes';

/**
* @type {number[]}
*/
const arrowKeys = [ RIGHT, UP, DOWN, LEFT ];

/**
* Normalizes the 'key' property of a KeyboardEvent in IE/Edge
*
Expand All @@ -11,7 +21,7 @@
export function normalizeArrowKey( event ) {
const { key, keyCode } = event;

if ( keyCode >= 37 && keyCode <= 40 && key.indexOf( 'Arrow' ) !== 0 ) {
if ( arrowKeys.includes( keyCode ) && key.indexOf( 'Arrow' ) !== 0 ) {
return `Arrow${ key }`;
}
return key;
Expand Down
29 changes: 29 additions & 0 deletions packages/components/src/utils/test/keyboard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* WordPress dependencies
*/
import { RIGHT, SPACE } from '@wordpress/keycodes';

/**
* Internal dependencies
*/
import { normalizeArrowKey } from '../keyboard';

describe( 'normalizeArrowKey', () => {
it( 'should return the Arrow(Key) version for the presed key', () => {
const e = new window.KeyboardEvent( 'keydown', {
key: 'Right',
keyCode: RIGHT,
} );

expect( normalizeArrowKey( e ) ).toEqual( 'ArrowRight' );
} );

it( 'should return the non-normalized version if given a non arrow key event', () => {
const e = new window.KeyboardEvent( 'keydown', {
key: 'Space',
keyCode: SPACE,
} );

expect( normalizeArrowKey( e ) ).toEqual( 'Space' );
} );
} );

0 comments on commit 7fd294c

Please sign in to comment.