React testing library: The given element does not have a value setter when fireEvent change on input form

前端 未结 3 1412
盖世英雄少女心
盖世英雄少女心 2021-02-12 09:27

I want to change the value of material UI TextField in react testing library. I already set up the data-testid. Then using getByTestId i picked up the

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 10:32

    Problem here is TextField is an abstraction in MaterialUI. It consists of FormControl, Label and Input. Clean way of solving this problem is:

    • First, add InputProps on your TextField, with data-testid attribute.
    // YourComponent.js
    
     setContent(event.target.value)}
      id="content"
      inputProps={{ "data-testid": "content-input" }}
      value={content}
      label="Content"
    />
    
    • Then simply query using this ID.
    // YourComponent.test.js
    
    const contentInput = getByTestId("content-input");
    fireEvent.change(contentInput, {
      target: { value: "new content" }
    });
    
    // and then assert stuff in here
    

提交回复
热议问题