I can't compare dates in my component testing in Angular

Viewed 175

I'm trying to testing a component, i have this scenario:

My components mount and call ngOnInit(). My ngOnInit() calls one function that set in variable startDate one date:

ngOnInit() {
   this.getActualDate()
}

getActualDate(){
   this.startDate = new Date()
   this.startDate.setHours(0, 0, 0)
}

I'm trying to test if my component is filling the variable startDate with a Date.

This is what i tried:

fit('should compare the date', () => {
   const startDate = new Date();
   startDate.setHours(0, 0, 0);
   spyOn(component, 'getActualDate');
   component.getActualDate();
   fixture.detectChanges();
   expect(component.startDate).toEqual(startDate);
})

When i run this test i get this error:

Expected Date(Thu Aug 06 2020 23:59:59 GMT-0300 (Horário Padrão de Brasília)) to equal Date(Thu Aug 06 2020 00:00:00 GMT-0300 (Horário Padrão de Brasília)).
1 Answers

The function toEqual() uses strict equality in its comparison. Which means an object is not considered equal to any other object, even if they seem identical.

console.log(new Date() === new Date()) // false. Even if they are very similar

You should compare only primitive properties of objects if your want to compare equivalence. You could also call toString() on the objects as string is a primitive type:

console.log(new Date().toString() === new Date().toString()) // true
Related