'How to test a DatePicker component using Jest?

Here is the component to test, its a DatePicker component:

import { useState } from 'react';
import { useFormContext } from '../Form';
import Textbox from '../Textbox';
import './styles.scss';

const DatePicker = () => {
  const { register } = useFormContext();
  const [inputType, setInputType] = useState('text');

  const date = new Date(Date.now());
  const minDate = new Intl.DateTimeFormat('en-US').format(date);

  return (
    <div className="will-dissolve-date-picker">
      <div className="col-md-6 tw-mb-2 tw-mt-12 tw-pl-0" id="dissolve-date-input-wrapper">
        <Textbox
          name="familyName"
          id="dissolve-date"
          type={inputType}
          onBlur={() => setInputType('text')}
          onFocus={() => {
            setInputType('date');
          }}
          label="Select A Date"
          min={minDate}
          {...register('dissolve-date')}
        />
      </div>
    </div>
  );
};

export default DatePicker;

What could be the possible test cases in such a scenario, should I test the submit handler,onBlur and onFocus etc?



Solution 1:[1]

Think of what an end user is going to do with this component in terms of interaction, changing values, onFocus, onBlur, on any event change externally or anything which may impact this component.

Now you have some use cases and these use cases result in something being updated on the Dom in the final state.

Also, some negative situations and how to gracefully handle them.

Now you have use cases and final expected results.

This is what you now write test cases for. The idea is to assert and verify what happens finally.

Note that it's important to think in the direction of what the outcome is and not worry about internal implementations when writing tests. It's an ideology which drives RTL especially and it's a good principle to follow.

I hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emmanuel Ponnudurai