I am facing an issue while trying to create a test helper function that simulates document key press events. Here is my current implementation:
export const simulateKeyPress = (key: string) => {
var e = new KeyboardEvent('keydown');
e.key = key;
e.keyCode = e.key.charCodeAt(0);
e.which = e.keyCode;
e.ctrlKey = true;
document.dispatchEvent(e);
};
However, TypeScript throws the following error:
TypeError: Cannot set property key of [object KeyboardEvent] which has only a getter
I attempted to resolve this by using the following code snippet but ended up with the same error:
type Mutable<T extends { [x: string]: any }, K extends string> = { [P in K]: T[P] };
export const simulateKeyPress = (key: string) => {
var e = new KeyboardEvent('keydown');
(e as Mutable<KeyboardEvent, keyof KeyboardEvent>).key = key;
(e as Mutable<KeyboardEvent, keyof KeyboardEvent>).keyCode = e.key.charCodeAt(0);
(e as Mutable<KeyboardEvent, keyof KeyboardEvent>).which = e.keyCode;
(e as Mutable<KeyboardEvent, keyof KeyboardEvent>).ctrlKey = true;
document.dispatchEvent(e);
};