【问题标题】:Can't access IonInput value inside the test无法在测试中访问 IonInput 值
【发布时间】:2021-09-24 17:39:12
【问题描述】:

如何使用反应测试库访问 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
    });
});

【问题讨论】:

标签: reactjs ionic-framework jestjs react-testing-library


【解决方案1】:

找到了解决此问题的方法。见例子。

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

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

【讨论】:

    【解决方案2】:

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

    要使测试工作,您必须明确查询输入元素:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多