【问题标题】:Unit testing a textfield using Formik with Jest / Enzyme使用 Formik 和 Jest / Enzyme 对文本字段进行单元测试
【发布时间】:2019-12-08 06:17:09
【问题描述】:

我完全迷失了对文本字段中的更改进行单元测试。我正在使用 jest + 酶来更改文本字段,但 policyEffectiveField.props().value 始终为空。

我尝试过模拟,但使用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);

但 policyEffectiveField.props().value 为空

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);
});

我期望期望(policyEffectiveField.props().value).toEqual(now);是真的,但我收到以下错误

change policyEffectiveDate textfield

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

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

  48 |     },
  49 |   });
> 50 |   expect(policyEffectiveField.props().value).toEqual(now);

【问题讨论】:

  • 您现在不应该也填充 whit 的值吗?但是,我不相信这会解决您的问题,我只是认为它代表了您想要测试的内容,因为您有一个硬编码的日期,但正在与运行测试时计算的日期进行比较。使用 Angular 测试,您通常需要运行摘要循环或更新,以便在测试时根据 Angular 所做的更新控件。您需要与此 formik 或 Jest/Enzyme 相同或相似吗?

标签: javascript reactjs jestjs enzyme formik


【解决方案1】:

Formik 在内部使用 setState。因此,在您的模拟()调用之后,您需要等待一个承诺(并使其回调异步),例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-28
    • 2021-06-24
    • 2019-10-26
    • 1970-01-01
    • 2018-12-16
    • 2020-08-27
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多