puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Date input testing in Angular (Notification) #31

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

It is very common that we have a Date Input component,

<input [matDatepicker]='date'
    [max]='max'
    [min]='min'></input>

<error [message] = 'message'
  *ngIf = '!validation'></error>

Therefore the above code is to display a date input component inside the template, which has a min value input and a max value input, when the user input exceeds the limit, then it will trig the validation === false, which will lead the message to be displayed inside the error tag.

Then we need to write the test for the date input.

it is very common that we set the like below, here we only test with max value

it('should display the error tag with corresponding error message when input is not valid', ( ) => {
    const message = ' value should not be larger than 01 Jan 1980 10:00:00 GMT';
    component.max = new Date ('01 Jan 1980 10:00:00 GMT');
    component.model = new Date('01 Jan 1990 10:00:00 GMT');
    fixture.detectChanges( );
    expect(component.validation).tobe(false);
    expect(component.message).tobe(message);
})

The above code will PASS the test, however, the logic is not correct.

Cause inside the message we set the value as ' value should not be larger than 01 Jan 1980 10:00:00 GMT', which means no matter where the user is, with which time zone, and runs this test, always obtains the same answer.

While, the actually real senario should be the message's time zone changes based on the user's time zone.

e.g.

var unixTimeZero = new Date('01 Jan 1990 00:00:00 GMT-2');

console.log(unixTimeZero);
===> Mon Jan 01 1990 03:00:00 GMT+0100 (Central European Standard Time)

The above console.log is done in GMT+1 timezone, therefore when the source date set as 00:00:00 GMT-2, it will display as 03:00:00 GMT+0100.

Thus for the test, we need to modify as following

it('should display the error tag with corresponding error message when input is not valid', ( ) => {
    const maxDate = new Date ('01 Jan 1980 10:00:00 GMT');
    const message = ` value should not be larger than  ${maxDate}`;
    component.max = maxDate
    component.model = new Date('01 Jan 1990 10:00:00 GMT');
    fixture.detectChanges( );
    expect(component.validation).tobe(false);
    expect(component.message).tobe(message);
})

Then now it is correct.