Can't access IonInput value inside the test

Viewed 458

How I access the value of IonInput field using react testing library. See my example, If I replace html text input instead of IonInput it's working fine.

import { useState } from 'react';
import { render, screen } from '@testing-library/react';
import { IonInput } from '@ionic/react';

function MyComponent() {
    const [value, setValue] = useState('123');
    return (
        <IonInput
            data-testid="test-input"
            value={value}
            onIonChange={(e) => setValue(e.detail.value)}
        />
    );
}

describe('Test MyComponent', () => {
    test('Test input change', () => {
        render(<MyComponent />);
        const input = screen.queryByTestId('test-input');

        expect(input.value).toBe('123');

        // This input.value be undefined
        console.log('input.value', input.value); // undefined
    });
});

enter image description here

2 Answers

Found a solution to this issue. See example.

import { useState } from 'react';
import { render, screen } from '@testing-library/react';
import { IonInput } from '@ionic/react';

function MyComponent() {
    const [value, setValue] = useState('123');
    return (
        <IonInput
            data-testid="test-input"
            value={value}
            onIonChange={(e) => setValue(e.detail.value)}
        />
    );
}

describe('Test MyComponent', () => {
    test('Test input change', () => {
        render(<MyComponent />);
        const input = screen.queryByTestId('test-input');
        // Use input.getAttribute('value')
        expect(input.getAttribute('value')).toBe('123');
    });
});

Can access any attribute like this.

You are querying the <ion-input/> element which has the data-testid, not the native <input/> element, that is why you don't get the value.

To make the test work you have to explicity query the input element:

describe('Test MyComponent', () => {
    test('Test input change', () => {
        render(<MyComponent />);
        const input = screen.getByRole('textbox');

        expect(input.value).toBe('123');
    });
});
Related