pmiranda
pmiranda

Reputation: 8450

React, testing for input placeholder

I have this html input:

<input
  id='palapa'
  className='amount'
  placeholder={props.placeholder}
  type='number'
/>

I know it needs a value and a onChange event, but right now I want to test the value of the placeholder, in other words, I will be checking if some certain props is being rendered.

I was trying this without succes:

const defaultProps = {
    options: [
      { value: 'CLP', label: 'CLP' },
      { value: 'USD', label: 'USD' }
    ],
    placeholder: 'thePlaceHolder',
    topMessage: 'topMessage'
};

//<CurrencyInput > returns the input from above

const rendered = render(<CurrencyInput {...defaultProps} />);
const input = rendered.getByLabelText('palapa');
console.log(input); // undefined, I'm trying to get here "thePlaceHolder"

Any hiny?

Upvotes: 1

Views: 3094

Answers (2)

Sarun UK
Sarun UK

Reputation: 6746

Try this approach,

 const defaultProps = {
      options: [
        { value: 'CLP', label: 'CLP' },
        { value: 'USD', label: 'USD' }
      ],
      placeholder: 'thePlaceHolder',
      topMessage: 'topMessage'
    };
    const {container} = render(<CurrencyInput {...defaultProps} />);
    const input = container.querySelector('#palapa');
    console.log(input.placeholder); // thePlaceHolder
    expect(input.placeholder).toBe('thePlaceHolder');

   --------------[or]----------------

  const rendered = render(<CurrencyInput {...defaultProps} />);
  const input = rendered.getByPlaceholderText('thePlaceHolder');
  console.log(input); //thePlaceHolder

Upvotes: 0

ourmaninamsterdam
ourmaninamsterdam

Reputation: 2462

Try const input = rendered.getByPlaceholderText('palapa'); (see https://testing-library.com/docs/dom-testing-library/api-queries/#byplaceholdertext)

getByLabelText will work if your input is wrapped/associated with a label

Upvotes: 1

Related Questions