首页 > 解决方案 > 为什么文本在反应中不匹配?

问题描述

我正在尝试写test case. functional component我只是写如果有必填字段会显示。但是required text我的测试没有通过为什么

it("get text of required field", () => {
    wrapper.setProps({
      error: {
        olmIdError: true
      }
    });
    console.log(wrapper.find(FormHelperText).text());
    expect(wrapper.find(FormHelperText).text()).toEqual("Required..!!");
  });

这是我的代码

https://codesandbox.io/s/43k6lw60x

零件

 <Input
            error={error.olmIdError || apiError}
            id="olm-id"
            type="text"
            value={olmId}
            classes={{
              root: classes.inputRoot,
              focused: classes.focusedLabel,
              underline: classes.underlineInput
            }}
            placeholder="Enter OLM ID"
            onChange={handleChange("olmId")}
          />
          {error.olmIdError ? (
            <FormHelperText error={error.olmIdError} id="weight-helper-text">
              {MESSAGES.REQUIRED}
            </FormHelperText>
          ) : null}

出错

Expected value to equal:
  "Required..!!"
Received:
  "<WithStyles(WithFormControlContext(FormHelperText)) />"

  44 |       }

在此处输入图像描述

标签: reactjsreact-reduxjestjsenzyme

解决方案


如果您将断言更改为,则测试通过

expect(wrapper.find(FormHelperText).children().text()).toEqual("Required..!!");

这是Codesandbox 工作

.text()返回当前树的渲染文本。输出有点奇怪,因为当前树是FormHelperText浅渲染的。调用.children()first 导致树只是Required..!!文本。


推荐阅读