Formik Material UI和反应测试库

时间:2019-03-25 06:06:52

标签: reactjs material-ui formik react-testing-library

我发现使用React测试库很难理解我要使用的查询,以选择需要测试的组件。当DOM在诸如材料ui和formik之类的框架中变得越来越冗长时,查询将变得过于简单。

我创建了一个代码沙箱来说明问题。您可以在那里检查失败的测试。

https://codesandbox.io/embed/px277lj1x

我遇到的问题是,查询getLabelTextBy()不返回该组件。材质ui似乎不显示aria标签或的for属性。不确定如何解决此错误。

下面的代码也可供参考

//Subject under test

import React from "react";
import { Button } from "@material-ui/core";
import { TextField } from "formik-material-ui";
import { Field, Form, Formik } from "formik";
import * as yup from "yup";

const validationSchema = yup.object().shape({
  name: yup.string().required("Office name is required"),
  address: yup.string().required("Address is required")
});

export default () => (
  <Formik
    initialValues={{
      name: "",
      address: ""
    }}
    validationSchema={validationSchema}
    onSubmit={(values, { setSubmitting }) => {
      setSubmitting(false);
      console.log("form is submitted with", values);
    }}
    render={({ submitForm, isSubmitting, isValid }) => (
      <Form>
        <Field
          label="Office Name"
          name="name"
          required
          type="text"
          component={TextField}
        />
        <Field
          label="Address Line 1"
          name="addressLine1"
          type="text"
          component={TextField}
        />
        <Button
          variant="contained"
          color="primary"
          fullWidth={false}
          size="medium"
          disabled={isSubmitting || !isValid}
          onClick={submitForm}
          data-testid="submitButton"
        >
          Submit
        </Button>
      </Form>
    )}
  />
);


// Test
import React from "react";
import { render, fireEvent } from "react-testing-library";
import App from "./App";

describe("Create Office Form tests", () => {
  it("button should not be disabled when all required fields are filled up", () => {
    const { getByLabelText, getByTestId, debug } = render(<App />);
    const values = {
      "office name": "office",
      address: "address 1"
    };
    for (const key in values) {
      const input = getByLabelText(key, { exact: false, selector: "input" });
      fireEvent.change(input, { target: { value: values[key] } });
    }
    const button = getByTestId("submitButton");
    expect(button.disabled).not.toBeDefined();
  });
});

1 个答案:

答案 0 :(得分:1)

您应该将id添加到Field中,因为标签的for属性期望它所引用的输入元素的ID:

        <Field
          id="myName"
          label="Office Name"   
          name="name"
          required
          type="text"
          component={TextField}
        />

一个有效的示例:https://codesandbox.io/s/rr1l0lk75n