1

I have the following code where I am only enabling a button if relevant data exists.

I am trying to test this by faking a change in the input field so that the relevant data is available.

But my simulation does not seem to work thus the data remains empty which in turn means my button remains disabled. Can I please get some help on what I am doing wrong please? Thank you.

Note that following code works where events fires as expected and updates. Just issue in writing test.

const [code1, setCode1] = useState(''); 

const cannotPress = () => !(code1);

const handleFieldChange = (event, updater) => {
    updater(event.target.value);
};

// in test, trying to simulate a value entered in this input so that the event fires and 
// updates code1's value thus making cannotPress=false. This would enable the button and pass test.
<input id="code1" value={code1} onChange={event => handleFieldChange(event, setCode1)} />
<button id='btn type="submit" disabled={cannotPress()} onClick={() => doSomething()}>Submit</button>

Test

describe('tests', () => {
  const wrapper = shallow(<MyApp info={info} />);
  it('simple test', () => {
    const btn = wrapper.find('button#btn'); // able to find button
    const input = wrapper.find('input#code1'); // able to find input (tested by placing in default values)
    console.log(input.props().value); // prints nothing as expected
    input.instance().props.onChange(({ target: { value: 'some fake data' } })); // expecting the event to trigger and change value for code1.
    console.log(input.props().value); // ISSUE: expected to print 'some fake data' but still empty.
    expect(btn.prop('disabled')).toBe(false); // fails cos input has no value thus disabled is still true
  });
});
karvai
  • 2,417
  • 16
  • 31

1 Answers1

0

I think you will need to simulate the event (using enzyme) rather then trying to manipulate the onChange() property directly.

Seems like a similar issue to: https://stackoverflow.com/a/37452043/10610784

Try the suggested solution

input.simulate('change', { target: { value: 'Hello' } })
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
fadzb
  • 429
  • 4
  • 9
  • Same outcome where the input's value is still empty after running the command you suggested. – karvai Jun 14 '20 at 20:00
  • I have a feeling the value may not be empty, but rather your reference to the element is stale. After the `input.simulate()` command above, execute `console.log(wrapper.find('input#code1').props().value)` . If the value is still empty, maybe try the same thing but with the previous way you attempted to simulate the event (using props.onChange() ) – fadzb Jun 25 '20 at 18:35