fireEvent.change不输入值

问题描述

我有一个非常简单的表格,其中有1个输入,目前正在对其进行测试。但是,我无法fireEvent.change()添加输入。

主要代码

function Submission(){
    // I understand that I can just simply do [name,setName] but in the future there will be more input,this is just for testing
    const [formData,setFormData] = useState({
        name: ''
    })
    
    const updateForm = (e) => {setFormData({ ...formData,[e.target.id]: e.target.value })};

    return (
        <div>
            <TextField id="name" type='string' label="Name" value={formData.name} onChange={(e)=>updateForm(e)} required/>
        </div>
    )
}

测试块

it('Can put enter value into the input',() => {
    const {getByLabelText} = render(<Submission/>);
    const input = getByLabelText(/name/i);
    fireEvent.change(input,{ target: { value: 'name' }});
    expect(input).toBe('name');
  });

错误

  ● Submission › Can put enter value into the input

    expect(received).toContain(expected) // indexOf

    Expected value:  "name"
    Received object: <input aria-invalid="false" class="MuiInputBase-input MuiInput-input" id="name" required="" type="string" value="" />

      72 |     const input = getByLabelText(/name/i);
      73 |     fireEvent.change(input,{ target: { value: 'name' }});
    > 74 |     expect(input).toContain('name');
         |                   ^
      75 |   });

解决方法

我通过设置解决了 const input = getByLabelText(/name/i); as HTMLInputElement;