3

To simplify, lets see this function getting date and returning a date modified (start of day):

const getStartOfDay = date => {
    const newDate = new Date(date);
  newDate.setHours(0, 0, 0, 0);
  return newDate;
}

Now I want to implement some tests with invalid values i.e: getStartOfDay(new Date("HELLO")); function returns Date(Invalid Date).

I tried to test like:

expect(util.getStartOfDay("hello")).toBe(new Date("hello"));

But I get:

Expected Date(Invalid Date) to equal Date(Invalid Date).

Same error with toEquals()...

Other dates I compare with getTime() but here I cant... So I get stucked...

Any idea of how can I test it?

joc
  • 1,336
  • 12
  • 31

2 Answers2

2

This happens because in JS NaN != NaN and invalid date has NaN time. So you can check that util.getStartOfDay("hello").getTime() is NaN

expect(isNaN(util.getStartOfDay("hello").getTime())).toBe(true);
Antonio
  • 901
  • 5
  • 12
1

With some insight from Detecting an "invalid date" Date instance in JavaScript.

const isValidDate = date => {
  if ( Object.prototype.toString.call(date) === "[object Date]" ) {
    // it is a date
    if ( isNaN( date.getTime() ) ) {  // date.valueOf() could also work
      return false;
    }
    else {
      return true;
    }
  }
  else {
    return false;
  }
}

describe("Suite", function() {
  it("handles invalid Dates", function() {
    expect(isValidDate(getStartOfDay("hello")) ).toBeFalsy();
  });
});

Here's the JSFiddle https://jsfiddle.net/backpackcoder/jj3061fk/1/

Community
  • 1
  • 1
backpackcoder
  • 327
  • 1
  • 7