首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置值并单击带有react-testing library的提交按钮

设置值并单击带有react-testing library的提交按钮
EN

Stack Overflow用户
提问于 2020-07-07 13:58:03
回答 2查看 367关注 0票数 0

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

代码语言:javascript
复制
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)看起来像(为简洁起见,我删除了它的大部分):

代码语言:javascript
复制
<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>

第一个角色是为了让TypeScript高兴。第二个主要是关于我使用fireEvent来模拟用户输入。你对如何测试这个功能有什么想法吗?现在,测试总是失败,因为它期望abc@def并接收'‘。

EN

回答 2

Stack Overflow用户

发布于 2020-07-07 18:50:32

因为您使用的是MUI组件的TextField组件,所以您不能使用getByLabelText获得真正的输入。相反,您应该使用getByPlaceholderText。试试这个:

代码语言:javascript
复制
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');
})

票数 0
EN

Stack Overflow用户

发布于 2020-07-09 02:47:20

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

代码语言:javascript
复制
// add a data-testid="myElement" on the TextField component

// in test:
fireEvent.change(getByTestId('myElement').querySelector('input'), { target: { value: 'abc@def' } });

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62768977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档