Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine .toHaveBeenCalledWith(aDate) not working

I'm inheriting some code, and I've got two of their tests that are still failing, not sure if they were before, or if it's because I have a different version of Jasmine (they were pre 2.0)

The test that is failing has this spy setup in the beforeEach

spyOn(datacontext, 'getImportLogForDate').and.callThrough();

Then in the test

controller.DepositDate = new Date();
controller.PerformActionThatCallsGetImportLogForDate();
expect(context.getImportLogForDate).toHaveBeenCalledWith('1', controller.DepositDate);

The resulting error is confounding because they are identical

Expected spy getImportLogForDate to have been called with [ '1', Date(Thu Dec 04 2014 13:00:51 GMT-0600 (Central Standard Time)) ] but actual calls were [ '1', Date(Thu Dec 04 2014 13:00:51 GMT-0600 (Central Standard Time)) ].

Can I not verify functions have been called with a Date?

like image 716
CaffGeek Avatar asked Oct 16 '25 00:10

CaffGeek


2 Answers

What is PerformActionThatCallsGetImportLogForDate doing with the date object? Jasmine compares date objects by their millisecond value so if it's off even by 1ms, they won't be equal, but you won't see that level of detail just reading the console output.

Alternatively, you have 2 other options.

Just test that a date object was used as the 2nd argument.

expect(context.getImportLogForDate)
    .toHaveBeenCalledWith('1', jasmine.any(Date));

Test that date value, but outside of a toHaveBeenCalledWith, in case of some specific weirdness with that matcher.

expect(context.getImportLogForDate.calls.mostRecent().args[0])
    .toEqual('1');
expect(context.getImportLogForDate.calls.mostRecent().args[1])
    .toEqual(controller.DepositDate);
like image 57
user2943490 Avatar answered Oct 19 '25 09:10

user2943490


I have found that when using toHaveBeenCalledWith for a specific Date, jasmine.objectContaining works great.

it('#userChangedMonth calls fetchData with end of month', () => {
    spyOn(component, 'fetchData').and.returnValue(true);
    const calendarChangedTo = new Date('2018-10-10 00:00:00');
    const endOfMonth = new Date('2018-10-31 23:59:59');
    component.userChangedMonth(calendarChangedTo);
    expect(component.fetchData).toHaveBeenCalledWith(jasmine.objectContaining(endOfMonth));
  });
like image 21
Gerald Spreer Avatar answered Oct 19 '25 10:10

Gerald Spreer