0
votes

I am totally lost with unit testing a change in a textfield. I'm using jest + enzyme to change the textfield but policyEffectiveField.props().value is always null.

I've tried to simulate but using 'change' and 'click' from the formik doc.

policyEffectiveField.simulate('change', {
    // you must add this next line as (Formik calls e.persist() internally)
    persist: () => {},
    // simulate changing e.target.name and e.target.value
    target: {
      name: 'policyEffectiveDate',
      value: "07/30/2019",
    },
  });
  expect(policyEffectiveField.props().value).toEqual(now);

But policyEffectiveField.props().value is null

it('change policyEffectiveDate textfield ', () => {
  let now = moment().format('L');
  var mountRTI = mount(<TestRTI forms={[policyEffectiveDate]} />);
  var policyEffectiveField = mountRTI.find(TextField).find('input').find({ name: 'policyEffectiveDate' });
  policyEffectiveField.simulate('change', {
    // you must add this next line as (Formik calls e.persist() internally)
    persist: () => {},
    // simulate changing e.target.name and e.target.value
    target: {
      name: 'policyEffectiveDate',
      value: "07/29/2019",
    },
  });
  expect(policyEffectiveField.props().value).toEqual(now);
});

I expected expect(policyEffectiveField.props().value).toEqual(now); to be true, but I am getting the below error

change policyEffectiveDate textfield

expect(received).toEqual(expected) // deep equality

Expected: "07/30/2019"
Received: undefined

  48 |     },
  49 |   });
> 50 |   expect(policyEffectiveField.props().value).toEqual(now);
1
Should you not be populating the value whit now as well? However, I do not believe this will fix your issue, I just think it represents what you want to test since you have a hard coded date, but are comparing against a date that will be calculated when your test is run. With Angular tests, you normally need to run a digest cycle, or an update so the control is updated based on what Angular would have done, when you are testing. Do you need the same or similar with this formik or Jest/Enzyme? - Steven Scott

1 Answers

0
votes

Formik uses setState internally. So, after your simulate() call, you need to await a promise (and make your it callback async), for example:

it("test", async () => {
      // simulate call here
      await new Promise(resolve => {
        setTimeout(resolve);
      });
      // assertion/other code here
})