如何对屏蔽输入进行单元测试



如何使用react测试库对屏蔽的输入字段进行单元测试。该组件是使用材料ui和反作用钩子形式开发的。在这里,您可以找到我这边的代码和示例。提前感谢

测试文件:

let Phone_Input = getByTestId("phone-input");
fireEvent.change(
<InputMask mask="(999) 999-9999">{() => Phone_Input}</InputMask>,
{
target: { value: "9500902621" }
}
);

组件:

<InputMask mask="(999) 999-9999">
{() => (
<TextField
id="standard-required"
name="phone"
label="phone"
placeholder="Enter Phone"
inputProps={{
"data-testid": "phone-input"
}}
/>
)}
</InputMask>

错误:

The given element does not have a value setter
expect(received).toBe(expected) // Object.is equality
Expected: "(950) 090-2621"
Received: "(___) ___-____"

所以,我在使用react-input-mask时遇到了同样的问题。经过长时间的搜索,我发现了这篇帖子:https://github.com/sanniassin/react-input-mask/issues/174.(仍然是库未解决的问题(

那里的人讨论了两种可能的解决方案:

  1. 更改库(react text mask,react imask…(

  2. 使用帖子创建者制定的变通方法:

例如:

import userEvent from '@testing-library/user-event';
import TestUtils from 'react-dom/test-utils';
function changeInputMaskValue(element, value) {
element.value = value;
element.selectionStart = element.selectionEnd = value.length;
TestUtils.Simulate.change(element);
};
it('example test', async () => {
render(
<MyComponent
amount="100.00"
/>,
);
act(() => {
// Both lines of codes are required
userEvent.type(screen.getByLabelText('Amount'), '300');
changeInputMaskValue(screen.getByLabelText('Amount'), '300');
});
act(() => {
// Do not move the form submitting to the previous `act`, it must be in two
// separate `act` calls.
userEvent.click(screen.getByText('Next'));
});
// You must use `findByText`
const error = await screen.findByText(/$100.00 to redeem/);
expect(error).toBeInTheDocument();
});

我的组件与您的组件不同,但可能会引导您走向正确的方向。

我的测试是这样的:

const propsMock = { mask: sampleMask };
const { getByTestId } = render(<MaskedTextField {...propsMock} />);
const input = getByTestId('maskedtextfield-');
fireEvent.change(input, { target: { value: '9999999999' } });
expect(getByTestId('maskedtextfield-').value).toEqual('(999) 999-9999');

重要部件:

<Input
placeholder={placeholder}
disabled={disabled}
onChange={onChange}
onKeyUp={onKeyUp}
onBlur={onBlur}
inputRef={inputRef}
inputComponent={TextMaskCustom as any}
inputProps={{
'data-testid': dataTestId || `maskedtextfield-${label}`,
defaultValue: defaultValue || '',
...getMaskProps(mask),
}}
/>

我的deps是:Input是一个材料ui组件,TextMaskCustomreact-text-mask的一个实现。在这里工作很好。

最新更新