0

I am trying to test a component with testing-library. The problem I'm facing is how to introduce text automatically in an input. Usually this could be achieved by:

const inputName = screen.getByPlaceholderText(/name/i)

fireEvent.click(inputName)
fireEvent.change(inputName, { target: { value: 'test name' } })

But in my case I am using the library cleave.js to format the input and seems that fireEvent.change is not able to introduce the text.

Does anyone know how to address this problem?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Andrés
  • 719
  • 1
  • 4
  • 21

2 Answers2

1

I would recommend you use @testing-library/user-event to test interactions like these.

Assuming you have the following component which renders a Cleave.js credit card input.

const TestComponent = () => {
  return (
    <Cleave placeholder="Enter CC number" options={{ creditCard: true }} />
  );
};

You could use @testing-library/user-event's type function in your test to simulate user's typing.

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');
});
juliomalves
  • 42,130
  • 20
  • 150
  • 146
0

this is how I got mine to work in a multistep form, where step 1 had a cleave.js component inside of it. Using react-hook-form for the form library

 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',
    testInput: '11'
  },
  {
    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

})
Vincent Tang
  • 3,758
  • 6
  • 45
  • 63