无法在测试中访问 IonInput 值

Can't access IonInput value inside the test

我如何使用 React 测试库访问 IonInput 字段的值。看我的例子, 如果我替换 html 文本输入而不是 IonInput,它工作正常。

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
    });
});

您正在查询具有 data-testid<ion-input/> 元素,而不是本机 <input/> 元素,这就是您没有获得值的原因。

要使测试正常进行,您必须明确查询输入元素:

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

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

已找到解决此问题的方法。参见示例。

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');
    });
});

可以像这样访问任何属性。