rootInstance.findByType("输入"); 给出预期 1 但发现 2 个节点类型为“未定义”的实例

C-o*_*des 5 reactjs react-test-renderer

所以我有一个显示一些文本字段的组件。一个输入,一个选择,根据用户在该选择上使用的输入,(选择的值)显示或不显示第三个。

我尝试使用 React-Test-Renderer 仅测试第一个输入字段,但出现以下错误:预期 1 但发现 2 个节点类型为“未定义”的实例

这是输入字段代码:

    <div>
      <div className="container">
        <h3 className="h3">Info</h3>
        <div className="row">
          <div className="col">
            <label htmlFor="test">test:</label>
            <input
              id="myID"
              value={aPropThatIsAnEmptyString}
              type="text"
              className={`form-control form-control-sm ${style.fieldsGap}`}
              onChange={e => setTest(e.target.value)}
              placeholder="test"
            />
          </div>
          <div className="col">
            <label htmlFor="ddlType">test2:</label>
            <select
              id="SelectId" 
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码:


 it("test input field", () => {
    const newProps = {
      something: initialState,
      dispatch: reducer
    };
    const component = TestRenderer.create(
      <ContextBR.Provider value={{ ...newProps }}>
        <ComponentWithTheFields/>
      </ContextBR.Provider>
    );
    const rootInstance = component.root;
    console.log(rootInstance);
    const inputField = rootInstance.findByType("input");

    inputField.props.onChange({ target: { value: "" } });
    expect(inputField.props.value).toBe("");

    inputField.props.onChange({ target: { value: "blue" } });
    expect(inputField.props.value).toBe("blue");
  });
Run Code Online (Sandbox Code Playgroud)

如果您想知道 ContextBR.Provider 是什么,我们使用 context 而不是 redux。

我的错误消息:预期 1 个,但发现 2 个节点类型为“未定义”的实例



  29 |     const rootInstance = component.root;
  30 |     console.log(rootInstance);
> 31 |     const inputField= rootInstance.findByType("input");
     |                                   ^
  32 | 
  33 |     inputField.props.onChange({ target: { value: "" } });
  34 |     expect(inputField.props.value).toBe("");
Run Code Online (Sandbox Code Playgroud)

我首先尝试了 ad 而不<ContextBr.Provider进行包装,但这给了我 Dispatch 为 null 或未定义。这可能是因为我也没有发送上下文并且组件使用它。

我期望它找到输入,并断言其值是否为我发送的值“”。之后,我的目标是添加重复的代码,而不是发送“”,而是发送“蓝色”(仅作为示例),然后对此进行断言。

我正在尝试测试用户体验。他可以在上面打字,并且它会显示他正在打字的内容。

小智 6

文档中

testInstance.findByType()

查找具有所提供类型的单个后代测试实例。如果没有恰好一个测试实例具有所提供的类型,则会抛出错误。

我的猜测是,您的组件中隐藏了多个输入字段,导致findByType()抛出错误。

您可以使用以下方式选择输入字段之一

rootInstance.findAllByType("input")[index] 
Run Code Online (Sandbox Code Playgroud)

注意:我不知道为什么 React 说类型未定义,但findAllByType()对我来说仍然有效。