【问题标题】:Test data structure with formik and react-testing-library使用 formik 和 react-testing-library 测试数据结构
【发布时间】:2020-07-05 02:09:02
【问题描述】:

我是 react-testing-library 的初学者,我正在寻找一种方法来比较 react-testing-library 和 Formik 中的对象。我想:

  • 提交表格
  • 并测试结构是否兼容
it("will check the matchers and pass", () => {
  const object = {
    timeInTheWeek: [
      "10:00",
      "10:00",
      "10:00",
      "10:00",
      "10:00",
      "10:00",
      "10:00",
    ],
    selected: true
  }

  expect(object).toMatchSnapshot({
    selected: expect.any(Boolean),
    timeInTheWeek: expect.any(Array),
  })
})

我已经制作了这个对象的快照,在提交表单后我应该如何比较这两个对象(一个来自快照,一个来自提交表单数据)?我应该渲染额外的文本区域并将其与.toHaveTextContent() 匹配吗?我不知道应该如何正确处理。

提前致谢

【问题讨论】:

  • 您不应该使用 react-testing-library 进行快照匹配。另外,您可以为您的 Formik 表单创建一个最小代码示例吗?我认为selected 属性对应于复选框。不确定timeInTheWeek
  • 那么我应该如何解决这个问题来测试表单的提交和测试数据结构呢?有什么想法吗?
  • 阅读我更新的评论。谢谢。
  • @BranislavLazic Selected 是复选框,timeInTheWeek 是 FieldArray。后来我调整了Formik代码。

标签: reactjs formik react-testing-library


【解决方案1】:

为您的测试命名,并从用户的角度执行测试

it("should have selected something and display time slots in a week", () => {
  const object = {
    timeInTheWeek: [
      "10:00",
      "10:00",
      "10:00",
      "10:00",
      "10:00",
      "10:00",
      "10:00",
    ],
    selected: true
  }

  // Render your form
  const { getByText } = render(<Form />);
  // Wait for form to get updates
  await wait();

  // Check whether the checkbox is true
  expect(getByText("Text in your checkbox").checked).toEqual(object.selected);
  // Check the value of the first field. You can e.g. generate `datatest-id's` using field indicies and prefix them with e.g. "time-in-the-week-id-".
  expect(getByTestId("time-in-the-week-id-0")).toBe(object.timeInTheWeek[0]);
});

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2019-11-11
    • 2019-06-14
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2022-06-22
    • 2019-08-29
    相关资源
    最近更新 更多