1

我发现很难使用反应测试库并理解我需要使用的查询来选择我需要测试的组件。当 DOM 使用 material ui 和 formik 等框架变得越来越冗长时,查询过于简单。

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

https://codesandbox.io/embed/px277lj1x

我得到的问题是,查询 getLabelTextBy() 不返回组件。看起来 aria 标签 by 或 for 属性未由材质 ui 呈现。不知道如何修复此错误。

代码也在下面供参考

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

4

1 回答 1

2

您必须添加一个idField因为标签的for属性需要它所引用的输入元素的 ID:

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

一个工作示例:

编辑 Formiq Yup Material UI 和 react 测试库

于 2019-03-25T17:57:14.533 回答