如何从jest测试套件中与React Native DateTimePicker交互

gab6jxml  于 2022-11-30  发布在  React
关注(0)|答案(1)|浏览(143)

我做了一个精简版的项目,它有一个简单的按钮,当按下按钮时,它会打开一个日期选择器。如果用户选择了一个日期,文本标签就会更新。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上的日期,并测试标签是否更新为选定的日期。

pexxcrt2

pexxcrt21#

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')
    
    // Utility function to prepare the date to be accepted by DatePicker's onChange method
    
    const createDateTimeSetEvtParams = (
      date: Date,
    ): [DateTimePickerEvent, Date] => {
      return [
        {
          type: 'set',
          nativeEvent: {
            timestamp: date.getTime(),
          },
        },
        date,
      ];
    };
        
    describe('Date Picker Tests', () => {
        it.only("changing the date of datepicker", async() => {
            
            // mock the function we expect to be called when date is changed
            let testFunction = jest.fn()

            // render the parent
            render(<App/>) 
    
            // Press the button to make the DatePicker visible
            fireEvent.press(screen.getByText("Show date picker!")) 
    
            // Generate new date
            let date = new Date()
    
            // Fire the onChange Event
            fireEvent(
                UNSAFE_getByType(DateTimePicker),
                'onChange',
                ...createDateTimeSetEvtParams(date),
            ))
            expect(testFunction).toHaveBeenCalled()
            
        
        })
        
   })

相关问题