gpt4 book ai didi

javascript - testing-library/react 如何在动态生成错误消息时测试无效输入

转载 作者:行者123 更新时间:2023-12-05 07:00:58 28 4
gpt4 key购买 nike

我在 React 中使用 Form。它有卡号字段。因此,如果用户输入“333”并进入一个选项卡,则会显示一条动态消息,“卡号需要是 16 位数字”。

我正在使用 @testing-library/react@9.5.0ts-jest@26.3.0 编写测试。

表单组件:

CardForm.ts

用户 React-text-mask,Material UI 来显示一个输入,该输入通过一个模式进行验证,该模式具有一种方法来查看输入值是否为 16 并返回一个错误,然后显示为帮助文本。

<form onSubmit={handleSubmit}>
<FormInput
name="cardNumber"
label="Card Number"
inputMode="numeric"
value={values.cardNumber}
placeholder="XXXX-XXXX-XXXX-XXXX"
validation={validationSchema.cardNumber}
mask={formMasks.cardNumber}
/>
<Button
type="submit"
disabled={!values.card || validationSchema.cardNumber.errors.length === 0}
>
CONFIRM CARD
</Button>
</form>

CardForm.test.tsx

import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import { CardForm } from '../components/Forms/CardForm';

const setup = () => {
const utils = render(<CardEmailForm />);
const input = utils.getByPlaceholderText('XXXX-XXXX-XXXX-XXXX');
return {
input,
...utils,
};
};

test('show error message when card number entered is less than 16 digits', async () => {


const { input, ...utils } = setup();

fireEvent.change(input, {
target: { value: '333' }, // I am giving the value 333 to the input
});

expect((input as HTMLInputElement).value).toBe('333 -    -    -    '); //works

/* if I lose focus from the input, the error message shows up as helper text at the bottom of the input as shown above */
fireEvent.blur(input);

/* now I am just expecting to read the error from the DOM based on h6 helper text, but this keeps giving me ERROR. */

expect(await utils.getByRole('heading')).toHaveTextContent(
'Card Number should be 16 numbers'
);
});


错误! enter image description here

 > 29 |     await screen.getByRole('heading');
| ^
30 | expect(screen.getByRole('heading')).toHaveTextContent(
31 | 'Card Number should be 16 numbers'
32 | );

at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:34:12)
at getMultipleElementsFoundError (node_modules/@testing-library/dom/dist/query-helpers.js:21:35)

谁能帮我写出 expect 语句,这样一旦我输入错误然后模糊处理,我就能从屏幕上读取错误?

最佳答案

如果您使用的是 MUI 输入/表单,我相信帮助文本包含在 HTML 段落元素中:

<p class="MuiFormHelperText-root Mui-error MuiFormHelperText-sizeMedium MuiFormHelperText-contained MuiFormHelperText-filled css-v7esy" id="outlined-error-helper-text-helper-text">Incorrect entry.</p>

MUI helper text screenshot

关于javascript - testing-library/react 如何在动态生成错误消息时测试无效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63974572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com