I have a piece of code I am trying to test that ultimately does this (simplified):
const startDateMoment = moment(startDate, 'DD-MM-YYYY');
this.parametersService.startDate = startDateMoment;
Where startDate is a string (gotten from the activatedRoute in Angular).
The parametersService has a setter for startDate, that calls next on a rxjs behaviorSubject:
set startDate(startDate: moment.Moment) {
this._startDateState.next(startDate);
}
In my Jest test I am trying to verify that the setter is called with the correct moment value. The piece of code I am testing is called from my ngOnInit method.
it('Should set the startDate in the parametersService', () => {
let setStartDateSpy: jest.SpyInstance;
setStartDateSpy = jest.spyOn(comp['parametersService'], 'startDate', 'set');
comp.ngOnInit();
expect(setStartDateSpy).toHaveBeenCalledTimes(1);
expect(setStartDateSpy).toHaveBeenCalledWith(<...?>);
});
I am not sure what to put in place of <...?> in my test. As you can see in my code sample, the setter is called with a moment. However the received value in the "toHaveBeenCalledWith" statement is somehow a string. I am not sure why this is happening. Note that in the actual code (outside of the test), this is a moment and not a string. Any insights into this would be appreciated.
If I ignore the fact that it's supposed to be a moment and test the code with a string value of '10-07-2019' like this:
expect(setStartDateSpy).toHaveBeenCalledWith(expect.stringContaining('2019-07-10'));
I get an error because moment is using my current timezone:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: StringContaining "2019-07-10"
Received: "2019-07-09T22:00:00.000Z"
I cannot set the timezone according to any of the examples found here, because I am running the tests from windows: Set moment timezone in Jest tests. Are there any other solutions to get the timezone to utc for just the tests?
Ideally I would like to test that the setter is called with a moment containing the correct date, however I don't know how I can do that.