我有一个InputAddressZipCode
仅用于 5 位美国邮政编码的组件。我可以onChangeText
使用react-test-renderer
and进行测试@testing-library/react-native
,但测试接受任何文本,例如 string ab
。但是,此输入应仅接受以下内容:
- 5 位数 (
maxLength={5}
) - 数字键盘 (
keyboardType="numeric"
)
如何使用 React Native 测试以下上述道具?
InputAddressZipCode.tsx:
// Imports: Dependencies
import React, { useState } from 'react';
import { TextInput } from 'react-native';
// Imports: TypeScript Types
import { IInputProps } from '../../types/inputTypes';
// Component: Input (Address: Zip Code)
const InputAddressZipCode = ({ placeholder, label, onChangeText, darkMode }: IInputProps): JSX.Element => {
// React Hooks: State
const [value, setValue] = useState<string>('');
// On Change
const onChange = (text: string): void => {
// Formatted Text: Numbers Only
const formattedText: string = text.replace(/[^0-9]/g, '');
// Set State
setValue(formattedText);
// Props: On Change Text
onChangeText(formattedText);
};
return (
<Input
value={value}
placeholder={placeholder || 'Zip Code'}
label={label ? label : 'Zip Code'}
keyboardType="numeric"
onChangeText={onChange}
autoCompleteType="postal-code" // Android Only
dataDetectorTypes="address" // iOS Only
textContentType="postalCode" // iOS Only
maxLength={5}
darkMode={darkMode || false}
/>
);
};
// Exports
export default InputAddressZipCode;
InputAddressZipCode.test.tsx:
// Imports: Dependencies
import React from 'react';
import renderer from 'react-test-renderer';
import { cleanup, render, fireEvent } from '@testing-library/react-native';
// Imports: Components
import InputAddressZipCode from '../InputAddressZipCode';
// Jest: Fake Timers (Replaces setTimeout, setInterval, clearTimeout, clearInterval Since They Depend On Real Time To Elapse)
jest.useFakeTimers();
// React Native Testing Library: Cleanup (Unmounts Component And Destroys Container)
afterEach(cleanup);
// Tests: Input (Address: Zip Code)
describe('Input (Address: Zip Code)', () => {
// Renders Component
it('renders component', () => {
renderer.create(<InputAddressZipCode placeholder="Placeholder" value="Value" onChangeText={() => null} darkMode={false} />);
});
// Changes Text
it('Changes Text', () => {
const onChangeTextMock = jest.fn();
const { getByPlaceholderText } = render(
<InputAddressZipCode placeholder="Placeholder" value="Value" onChangeText={onChangeTextMock} darkMode={false} />,
);
fireEvent(getByPlaceholderText('Placeholder'), 'onChangeText', '92694');
expect(onChangeTextMock).toHaveBeenCalledWith('92694');
});
// Changes Text
it('Changes Text (Numbers only)', () => {
const onChangeTextMock = jest.fn();
const { getByPlaceholderText } = render(
<InputAddressZipCode placeholder="Placeholder" value="Value" onChangeText={onChangeTextMock} darkMode={false} />,
);
fireEvent(getByPlaceholderText('Placeholder'), 'onChangeText', 'ab');
expect(onChangeTextMock).toHaveBeenCalledWith('');
});
});