How to simulate an onKeyDown event using Jest / Enzyme?

Viewed 249

I am creating a simple calculator with Javascript/ReactHooks, which has an input box with a onKeyDown attribute:

// from Calculator.js, in the return statement
<input id="input" value={inputLine} type="text" onKeyDown={(i) => setInputLineFromKeydown(i)} readOnly></input>

The setInputLineFromKeydown function handles displaying what is typed in the input box and looks for important keys such as "Enter" or "=" (to know when to start calculating). Here is where I'm trying to test it using Jest/Enzyme:

// from Calculator.test.js
const wrapper = shallow(<Calculator />);
it('should be able to call setInputLineFromKeydown', () => {
    wrapper.find('input').simulate('keypress', {key: '1'});
    wrapper.find('input').simulate('keypress', {key: '+'});
    wrapper.find('input').simulate('keypress', {key: '2'});
    wrapper.find('input').simulate('keypress', {key: 'Enter'});
});    

Although this test 'passes', I can see from my code coverage that the keys aren't being pressed (Below is code from my Calculator.js flie, test coverage shows that the line that includes "i.key === 'Enter'" is not covered)

// from Calculator.js
const setInputLineFromKeydown = (i) => {
        let screen = document.getElementById("input");
        i.persist();

        if (isFinite(i.key) ||
            (i.key === "+" || i.key === "-" || i.key === "*" || i.key === "/"
           || i.key === "=" || i.key === "Enter" || i.key === "c")) {

            setInputLine(inputLine + i.key);
...
}

Why is the simulate keypress not working properly?

0 Answers
Related