我在反应中使用表格。它有卡号字段。因此,如果用户输入“333”并进入选项卡,则会显示一条动态消息,显示“卡号必须是 16 位数字”。
我正在使用@testing-library/react@9.5.0
and编写测试ts-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'
);
});
> 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)
有人可以帮我写期望语句,这样一旦我输入错误然后模糊,我就可以从屏幕上读取错误吗?