@@ -56,6 +56,7 @@ import {
5656 registerLocale ,
5757 isMonthYearDisabled ,
5858 getDefaultLocale ,
59+ safeToDate ,
5960} from "../date_utils" ;
6061
6162registerLocale ( "pt-BR" , ptBR ) ;
@@ -1733,4 +1734,67 @@ describe("date_utils", () => {
17331734 expect ( typeof result ) . toBe ( "boolean" ) ;
17341735 } ) ;
17351736 } ) ;
1737+
1738+ describe ( "safeToDate" , ( ) => {
1739+ it ( "returns the date when given a valid Date object" , ( ) => {
1740+ const date = new Date ( "2024-01-15" ) ;
1741+ const result = safeToDate ( date ) ;
1742+ expect ( result ) . toBe ( date ) ;
1743+ } ) ;
1744+
1745+ it ( "returns null when given null" , ( ) => {
1746+ const result = safeToDate ( null ) ;
1747+ expect ( result ) . toBeNull ( ) ;
1748+ } ) ;
1749+
1750+ it ( "returns null when given undefined" , ( ) => {
1751+ const result = safeToDate ( undefined ) ;
1752+ expect ( result ) . toBeNull ( ) ;
1753+ } ) ;
1754+
1755+ it ( "returns null when given a string" , ( ) => {
1756+ // TypeScript types this as Date, but at runtime it could be a string
1757+ const result = safeToDate ( "2024-01-15" as unknown as Date ) ;
1758+ expect ( result ) . toBeNull ( ) ;
1759+ } ) ;
1760+
1761+ it ( "returns null when given an invalid date string" , ( ) => {
1762+ const result = safeToDate ( "not-a-date" as unknown as Date ) ;
1763+ expect ( result ) . toBeNull ( ) ;
1764+ } ) ;
1765+
1766+ it ( "returns null when given an Invalid Date object" , ( ) => {
1767+ const invalidDate = new Date ( "invalid" ) ;
1768+ expect ( isValid ( invalidDate ) ) . toBe ( false ) ;
1769+ const result = safeToDate ( invalidDate ) ;
1770+ expect ( result ) . toBeNull ( ) ;
1771+ } ) ;
1772+
1773+ it ( "returns null when given a number" , ( ) => {
1774+ const result = safeToDate ( 1705276800000 as unknown as Date ) ;
1775+ expect ( result ) . toBeNull ( ) ;
1776+ } ) ;
1777+
1778+ it ( "returns null when given an object that is not a Date" , ( ) => {
1779+ const result = safeToDate ( { year : 2024 , month : 1 } as unknown as Date ) ;
1780+ expect ( result ) . toBeNull ( ) ;
1781+ } ) ;
1782+
1783+ it ( "returns the date when given a Date created from newDate()" , ( ) => {
1784+ const date = newDate ( ) ;
1785+ const result = safeToDate ( date ) ;
1786+ expect ( result ) . toBe ( date ) ;
1787+ } ) ;
1788+
1789+ it ( "returns the date when given a Date at epoch" , ( ) => {
1790+ const date = new Date ( 0 ) ;
1791+ const result = safeToDate ( date ) ;
1792+ expect ( result ) . toBe ( date ) ;
1793+ } ) ;
1794+
1795+ it ( "returns null when given an empty string" , ( ) => {
1796+ const result = safeToDate ( "" as unknown as Date ) ;
1797+ expect ( result ) . toBeNull ( ) ;
1798+ } ) ;
1799+ } ) ;
17361800} ) ;
0 commit comments