我做了一个精简版的项目,它有一个简单的按钮,当按下按钮时,它会打开一个日期选择器。如果用户选择了一个日期,文本标签就会更新。datePicker的onChange函数调用另一个函数。我如何从jest与datePicker交互,即改变值并测试标签是否更新?
这是我的应用程序:
import React from 'react';
import {useState} from "react"
import { Platform, Button, Text, View} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
const App = () => {
const [date, setDate] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const onChange = (event, selectedDate) => {
const currentDate = selectedDate;
setShow(false);
setDate(currentDate);
testFunction()
};
const showMode = (currentMode) => {
if (Platform.OS === 'android') {
setShow(true);
}
setMode(currentMode);
};
const showDatepicker = () => {
showMode(mode);
};
function testFunction(){
console.log("testFunction called")
}
return (
<View style={{
flex: 1,
justifyContent: "center",
alignItems: "center"
}}>
<Button style={{margin:50}} onPress={showDatepicker} title="Show date picker!" />
<Text>selected: {date.toLocaleString()}</Text>
{show && (
<DateTimePicker
testID="dateTimePicker"
value={date}
mode={mode}
is24Hour={true}
onChange={onChange}
/>
)}
</View>
);
};
export default App;
这是我的考验
import React from 'react';
import renderer from 'react-test-renderer';
import {fireEvent, render, screen, waitFor, userEvent} from '@testing-library/react-native';
import App from "../app"
jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper')
describe('Date Picker Tests', () => {
it.only("changing the date of datepicker", async() => {
let journal = render(<App/>)
let text = screen.getByText("Show date picker!")
fireEvent.press(text)
let p = screen.getByTestId("dateTimePicker")
console.log(p)
})
})
我得到错误Unable to find an element with testID: dateTimePicker
因此,我想知道,如何更改DatePicker上的日期,并测试标签是否更新为选定的日期。
1条答案
按热度按时间pexxcrt21#