【问题标题】:Setting value and clicking a submit button with react-testing-library使用 react-testing-library 设置值并单击提交按钮
【发布时间】:2020-10-27 08:09:51
【问题描述】:

不幸的是,我有一个测试揭示了我对如何使用 react-testing-library 测试这个 React Web 应用程序的一些严重误解。测试:

const setup = () => {
    const utils = render(<UnderConstruction />)
    const input = utils.getByLabelText('Email')
    return {
        input,
        ...utils,
    }
}

test('It should set the email input', () => {
    const { input } = setup();
    const element = input as HTMLInputElement;
    fireEvent.change(element, { target: { value: 'abc@def' } });
    console.log(element.value);
    expect(element.value).toBe('abc@def');
})

简单的组件(使用 marterial-ui)看起来像(为简洁起见,我删除了大部分):

<form noValidate autoComplete="off" onSubmit={handleSubmit}>
    <TextField
        id="email-notification"
        name="email-notification"
        label="Email"
        value={email}
        onInput={(e: React.FormEvent<EventTarget>) => {
            let target = e.target as HTMLInputElement;
            setEmail(target.value);
        }}
        placeholder="Email" />
    &nbsp;
    &nbsp;
    <Button
        type="submit"
        variant="contained"
        color="secondary"
    >
        Submit
    </Button>
</form>

首先 as cast 是为了让 TypeScript 满意。其次主要是围绕我使用fireEvent来模拟用户输入。关于如何测试此功能的任何想法?现在测试失败了,因为它期待 abc@def 并接收 ''。

【问题讨论】:

    标签: reactjs jestjs material-ui react-testing-library


    【解决方案1】:

    使用这样的 UI 库,如果 getByLabelText 或 getByPlaceholderText 不起作用,我通常这样获取底层输入元素:

    // add a data-testid="myElement" on the TextField component
    
    // in test:
    fireEvent.change(getByTestId('myElement').querySelector('input'), { target: { value: 'abc@def' } });
    

    虽然这并不理想,但应尽可能使用 getByLabelText 或 getByPlaceholderText。

    【讨论】:

      【解决方案2】:

      因为你使用的是MUI Component的TextField组件,所以你不能用getByLabelText得到真正的输入。取而代之的是,您应该使用getByPlaceholderText。 试试这个:

      const setup = () => {
          const utils = render(<UnderConstruction />)
          const input = utils.getByPlaceholderText('Email')
          return {
              input,
              ...utils,
          }
      }
      
      test('It should set the email input', () => {
          const { input } = setup();
          const element = input as HTMLInputElement;
          fireEvent.change(element, { target: { value: 'abc@def' } });
          console.log(element.value);
          expect(element.value).toBe('abc@def');
      })

      【讨论】:

      • 感谢您的意见。这对我也不起作用。
      • 我从图片中取出 material-ui 进行了测试,我发现如果我初始化输入(通过值属性/属性 - value="xxx"),那么我会得到与材料-ui 文本字段。但是,如果我关闭此属性/属性,那么我会得到预期的行为 - 输入值已更改。关于如何补偿初始值的任何想法?
      • @KevinBurton emailTextField 中的初始值是多少?
      猜你喜欢
      • 2020-04-09
      • 2021-07-18
      • 2020-05-09
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 2019-07-07
      相关资源
      最近更新 更多