如何解决使用 testing-library 测试 cleave.js 组件
我正在尝试使用测试库测试组件。我面临的问题是如何在 input
中自动引入文本。通常这可以通过以下方式实现:
const inputName = screen.getByPlaceholderText(/name/i)
fireEvent.click(inputName)
fireEvent.change(inputName,{ target: { value: 'test name' } })
但就我而言,我使用库 cleave.js
来格式化输入,似乎 fireEvent.change
无法引入文本。
有人知道如何解决这个问题吗?
解决方法
我建议您使用 @testing-library/user-event
来测试此类交互。
假设您有以下呈现 Cleave.js 信用卡输入的组件。
const TestComponent = () => {
return (
<Cleave placeholder="Enter CC number" options={{ creditCard: true }} />
);
};
您可以在测试中使用 @testing-library/user-event
的 type
函数来模拟用户的输入。
import { screen,render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
it('tests formatted input',() => {
render(<TestComponent />);
const input = screen.getByPlaceholderText('Enter CC number');
userEvent.type(input,'123412345123456');
expect(input.value).toBe('1234 12345 123456');
});
,
这就是我如何以多步形式工作,其中第 1 步在其中包含一个 cleave.js 组件。表单库使用 react-hook-form
it('should test formatted input',async () => {
const { getByTestId } = render(<ProviderTestComponent><Step1 {...defaultProps} /></ProviderTestComponent>)
const arrayOfInputs = [
{
dataTestId: 'test',testInput: '12345'
},{
dataTestId: 'test.day',testInput: '11'
},{
dataTestId: 'test.month',{
dataTestId: 'test.year',testInput: '1950'
},]
arrayOfInputs.forEach((item) => {
const inputField = getByTestId(item.dataTestId)
userEvent.type(inputField,item.testInput)
})
const nextButton = getByTestId('step1-next')
fireEvent.click(nextButton)
await waitFor(() => expect(handleOnSubmitMock).toHaveBeenCalled())
// ^ this needs to be awaited else the validation won't run for react-hook-form before cleave.js is finished
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。