简体   繁体   中英

Testing Luxon Datetime with React Testing Library results in error if calling Luxon functions

I could not find the answer for this question so please if duplicate please remove.

I have React (17.0.26) component that is using React Hook form (7.22.5) and Luxon (2.3.1).

This is the component definition itself is something like this (cannot provide full component code):

const CreateAppointmentForm = () =>{

  const currentDate = Datetime.now();

 const form = useForm<FormSchema>({
    resolver: (values, ...rest) => formSchema(values as FormSchema, ...rest),
    defaultValues: {
      endTime: currentDate.plus({ minute: 15 }),
      startTime: currentDate,
    },
  });
}
  const starTime = watch('startTime');
  const endTime = watch('endTime');
  const duration = endTime.diff(starTime, 'minutes').minutes;

return <div>{duration}</div>
}

When I try to run the test with React Testing library to just test the component I get the following error: Error: Uncaught [TypeError: endTime.diff is not a function]

If I log the object I can see a valid date time object (however it seems it is missing some properties) as can be seen the image below: 在此处输入图像描述

Im also using Typescript and node is on version 16.16.0.

React hook form only deals with strings.

The reason the Date object work with RHF is because it internally calls toString and Symbol(Symbol.toPrimitive) methods on the object.

Not part of the original question, But if you want to make RHF work with complex objects, then simply override these methods.

Either by defining them, making a new class, or via using a proxy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM