Angular 5 unit test using new Date to check date


I'm trying to test a service function in Angular where it receives a date and check if the date is a date in the future. If it is, it returns true.

// The 'check_date' will always be in the format `dd/mm/yyyy` public checkDate(check_date: string): boolean { const today: any = new Date(); const dateParts: any = check_date.split('/'); const dateObject: any = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]); if (dateObject.getTime() > today.getTime()) { return true; } return false; }

How can I test this? Because if I do something like this:

it('should return true if date is in the future', () => { const date = '04/02/2018'; const result = service.checkDate(date); expect(result).toBeTruthy(); });

Today it will pass, because new Date() will be 01/02/2018. But if I run this test next month, it will not pass.

I could set the date to be test to be way further in the future, like 01/01/3018. But I'd like to know if there is another method to test this case.


Date can be mocked to definitely test values it is supposed to return:

const UnmockedDate = Date; spyOn(<any>window, 'Date').and.returnValues( new UnmockedDate('2018-01-01'), new UnmockedDate('2018-02-04') ); const result = service.checkDate('04/02/2018'); expect(Date).toHaveBeenCalledTimes(2); expect(Date.calls.all()[0].object instanceof UnmockedDate).toBe(true); // called with new expect(Date.calls.argsFor(0)).toEqual([]); expect(Date.calls.all()[1].object instanceof UnmockedDate).toBe(true); expect(Date.calls.argsFor(1)).toEqual([...]); ...

Alternatively, Jasmine Clock API can be used to mock date:

jasmine.clock().install(); jasmine.clock().mockDate('2018-01-01'); const result = service.checkDate('04/02/2018'); ... jasmine.clock().uninstall(); // better be performed in afterEach

Since Date is not a spy, the test won't be as strict as the one where Date calls can be asserted.


Take a look at sinon fake timer:

describe('Date.now dependent test', () => { let clock; before(() => { clock = sinon.useFakeTimers({ now: 1483228800000 }); }); after(() => { clock.restore(); }); it('test', () => { const now = Date.now(); //now should always be 1483228800000 here }); })

It is based on https://github.com/sinonjs/lolex, which overrides native Date is a special way.


Usually I will just modify the input state for the SUT and call it a day:

let tomorrow = new Date().addDate(1); let fnSpy = spyOn(service, 'funcToTest'); expect(fnSpy).toBe(true);

That should always ensure that the date being tested in the SUT is greater than the whatever "today" is at the time the test is ran.

Note: You may need to convert "tomorrow" to a string for your use case.

hope this helps.



  • Angular 5 unit test using new Date to check date
  • How to compile my python code in cython with external python libs like pybrain
  • Updating a 'master' JSON object by adding data to a subobject
  • How to signing Android APK
  • GitLab Continuous Deployment to Azure Web App
  • How to debug component/typescript code when running Protractor
  • First dynamically-added TinyMCE editor displays, others do not
  • how to add dashed border on highcharts “area” graph for every point
  • Autocomplete source from project settings
  • Ruby on Rails: Get mediaplayer information (iTunes, TRAKTOR, Cog; current song + playlist)
  • How to use Flask's render_template from an ajax POST form submit
  • How to resolve this in PHPUnit where it is asking me to set KERNEL_DIR in my phpunit.xml?
  • Generate and export point cloud from Project Tango
  • When to use the tag in the head and body section of a html page? [duplicate]
  • Tensorflow Dataset API restore Iterator after completing one epoch
  • How to use Kaminari pagination gem with Sinatra and Mongoid?
  • Runtime complexity of getting the length of a string in different representations
  • JavaScript Regex to Match Boundaries of Words with diacritics
  • How to specify generic type when the type is only known at runtime?
  • Android: Unable to detect vertical plane
  • How to integrate angular2-material (alpha 8.2) with angular2-Quickstart app
  • VSTS work items list through REST API
  • Bind selectedDates Aggregation for Calendar
  • Debug `Unexpected end of JSON input Error` on content script
  • Apple Mach-O Linker error (“duplicate symbol”)
  • How to get rgb from transparent pixel in js
  • Computing the discrete fourier transform of audio data with FFTW
  • Why my AngularJS async test in Jasmine 1.3.x is not working?
  • Passing value from popup window to parent form's TextBox
  • Call Microservice from another Microservice within Docker
  • Android Library Projects on Windows and Mac
  • multiple button click in asp.net MVC 3
  • Angular FormGroup won't update it's value immediately after patchValue or setValue