How to test if date parameter is greater than the current date and throw an error using jest

Viewed 1003

I'm having a hard time testing the if condition, really not sure where the if condition has been triggered or how to trigger it. Here is the method

validateCapturedDate(capturedAt) {
    const currentDateTime = new Date()
    if (capturedAt > currentDateTime) {
        throw new Error(`"capturedAt" has value greater than current date`)
    }
}
1 Answers

In JS First, we can convert the Date into a numeric value by using getTime() function. By converting the given dates into numeric value we can directly compare them. Even you should also apply test on 'captureAt' field to test whether it is date object or not, and then should use getTime() pn it.

validateCapturedDate(capturedAt) { 
    const currentDateTime = new Date()

    if (capturedAt.getTime > currentDateTime.getTime) {
        throw new Error(`"capturedAt" has value greater than current date`)
    }
}
Related