Search code examples
reactjsenzymejestjs

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?


Solution

  • 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.