I have the following test in a angular (4) -
it('should call service',
async(inject([CommentTableComponent], (cmp: CommentTableComponent) => {
spyOn(mockSock, 'getComments').and.callThrough();
cmp.ngOnInit();
expect(mockSock.getComments).toHaveBeenCalledWith('api/jobs/604', moment());
})));
which throws the error:
Expected spy getComments to have been called with [ 'api/jobs/604', Sat Apr 29 2017 12:31:07 GMT+0100 ] but actual calls were [ 'api/jobs/604', Sat Apr 29 2017 00:00:00 GMT+0100, Sat Apr 29 2017 12:31:07 GMT+0100 ].
As these strings are clearly identical, I assume this is because the test value of now is several milliseconds later than the value when the component was running and the milliseconds aren't parsed into the string.
So my question is, how can I make my test work, is there a way to check the parameter called with is within x milliseconds of the current time?
Try this:
var spy = spyOn(mockSock, 'getComments').and.callThrough();
var today = moment('2017-4-29').toDate();
jasmine.clock().mockDate(today);
expect(spy.calls.mostRecent().args[0]).toEqual('api/jobs/604');
expect(spy.calls.mostRecent().args[1].valueOf()).toEqual(today.valueOf());
Reference: https://jasmine.github.io/2.5/introduction.html#section-Jasmine_Clock