Lennert Hofman
Lennert Hofman

Reputation: 595

How to find nested element in jest by value of attribute

I have a component with a Form and multiple Form.Field (sementic-ui-react) elements. I want to find a Form.Field element by the text of the label inside the element.

AddItem.js

class AddItems extends Component {
    ...
    render() {
      return (
        <div>
          <h1>Add Item</h1>
          <Form error onSubmit={this.handleSubmit.bind(this)}>
            <Form.Field>
              <label>Type</label>
            </Form.Field>
            ...

Instead of just using .first(), .at(1) ... I'd like to find a Form.Field element based on the text in the label ('Type').

Can this be done? If so, how?

Upvotes: 0

Views: 9201

Answers (2)

Garvae
Garvae

Reputation: 728

I'm using Jest + React testing library and this is my solution below:

it('your test', () => {
  const { container } = render((<YourComponent/>));
  /*                     ↓ ↓ ↓ the way you like to get all the elements you want to check for an attribute value  */
  const el = container.querySelectorAll('div').find(div => div.getAttribute('your-attribute') === 'value-to-search');
  expect(el) /* .toBeInTheDocument() for example */
});

Upvotes: 0

Lennert Hofman
Lennert Hofman

Reputation: 595

Nevermind, turns out I had a correct answer.

const findField = (text) => {
  return form.find(Form.Field).filterWhere((field) => {
    return field.find('label').text() === text;
  });
}
const titleField = findField('Type');
expect(titleField.find('input').first().props().name).toBe('type');

I just used Input instead of 'input' :P If anyone knows a better way, be sure to tell me.

Upvotes: 1

Related Questions