开发者问题收集

React,测试输入占位符

2020-11-18
3003

我有这个 html 输入:

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

我知道它需要一个 value 和一个 onChange 事件,但是现在我想测试占位符的值,换句话说,我将检查是否正在呈现某些 props

我尝试过这个但没有成功:

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"

有什么提示吗?

2个回答

尝试 const input = render.getByPlaceholderText('palapa'); (请参阅 https://testing-library.com/docs/dom-testing-library/api-queries/#byplaceholdertext

如果您的 input 被包裹/与 label 关联,则 getByLabelText 将起作用

ourmaninamsterdam
2020-11-18

尝试这种方法,

 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
Sarun UK
2020-11-18