How do I cover the test cases for useState hook in React Jest

Viewed 31

I have been writing code for a reusable date range picker which lets users set startDate and endDate and comes with an Apply button and dropdown options including ( Today, Tomorrow, This Month, etc ) for filling up the selector automatically .

While the basic functionalities are covered by the test cases written, it shows just 50% of the test cases are covered.

The uncovered line numbers are,

const onStartDateChange = value => {
    setStartAndEndDate(prev, { ...prev, startDate: value });
    setIsButtonDisabled(false);
};

Here, jest --coverage shows the line setStartAndEndDate(... not being covered by the test cases.

A little note is, the onStartDateChange is not coming from the props but resides inside the component itself.

The usage for the component is like,

<DateRangePicker enableTime onApplyClick={onApplyButtonClickMock} />

How do I cover the the function that is called when the date is picked from the calendar or ( from the dropdown ) startDate date picker is .

Minimal Reproducible Scenario: https://stackblitz.com/edit/react-sn2uhv

import React, { useState } from 'react';
import './style.css';

export default function App() {
  const [startAndEndDate, setStartAndEndDate] = useState({
    startDate: new Date(),
    endDate: new Date(new Date().setDate(new Date().getDate() + 1)),
  });

  const onStartTimeChange = (e) => {
    // How do I cover the line number 12 below...
    setStartAndEndDate((prev) => ({ ...prev, startDate: e.target.value }));
  };

  console.log(startAndEndDate);

  return (
    <div>
      <input onChange={onStartTimeChange} name="start-date" type="date" />
      <input name="end-date" type="date" />
    </div>
  );
}
0 Answers
Related