0

I encountered a problem during the TDD process and the state of react hooks did not change as expected

// Header.tsx

import React, { useState, ChangeEvent, KeyboardEvent } from 'react';

interface Props {
  addUndoItem: (item: string) => void;
}

function Header(props: Props) {
  const [value, setValue] = useState('');

  const handleChange = (e: ChangeEvent<{ value: string }>) => {
    setValue(e.target.value);
  };

  const handleKeyUp = (e: KeyboardEvent) => {
    if (value && e.keyCode === 13) {
      props.addUndoItem(value);
    }
  };

  return (
    <div>
      <input
        onChange={handleChange}
        onKeyUp={handleKeyUp}
        value={value}
        data-test="input"
      />
    </div>
  );
}

// tests/Header.tsx

it('the fn may invoked when press enter', () => {
      const userInput = 'test';
      const fn = jest.fn();
      const wrapper = shallow(<Header addUndoItem={fn} />);
      const inputEle = wrapper.find('[data-test="input"]');

      inputEle.simulate('change', {
        target: {
          value: userInput
        }
      });

      inputEle.simulate('keyUp', {
        keyCode: 13
      });
      expect(fn).toHaveBeenCalled();
      expect(fn).toHaveBeenCalledWith(userInput);
    });

when exec simulate change, the value in Header hooks is still '' it should be test, it run successful in browser

the error is

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

  48 |         keyCode: 13
  49 |       });
> 50 |       expect(fn).toHaveBeenCalled();
     |                  ^
  51 |       expect(fn).toHaveBeenCalledWith(userInput);
  52 |     });
  53 | 
ender
  • 1
  • 1
  • Does this answer your question? [When should you use render and shallow in Enzyme / React tests?](https://stackoverflow.com/questions/38710309/when-should-you-use-render-and-shallow-in-enzyme-react-tests) – Arnaud Claudel Feb 17 '20 at 15:34

1 Answers1

0

You need to use mount instead of shallow, otherwise your input component won't be properly rendered and therefore won't be usable during the test.

Arnaud Claudel
  • 3,000
  • 19
  • 25