We are using jest for mocking. I have a function which will greet us based on the time that file looks like below:
export default function getGreetingMessage() {
const today = new Date();
const curHr = today.getHours();
if (curHr < 12) {
return 'Good morning';
} else if (curHr < 18) {
return 'Good afternoon';
}
return 'Good evening';
}
And My test file will look like below
import getGreetingMessage from '../messages';
describe('messages', () => {
function setup(date) {
const DATE_TO_USE = new Date(date);
global.Date = jest.fn(() => DATE_TO_USE);
}
it('should return good afternoon when time is greater than 12', () => {
setup('Tue Oct 16 2018 15:49:11');
expect(getGreetingMessage()).toEqual('Good afternoon');
});
it('should return good morning when time is less than 12', () => {
setup('Tue Oct 16 2018 10:49:11');
expect(getGreetingMessage()).toEqual('Good morning');
});
it('should return good evening when time is greater than than 19', () => {
setup('Tue Oct 16 2018 19:49:11');
expect(getGreetingMessage()).toEqual('Good evening');
});
});
When I ran each test individually it's working fine. When I ran all at a time then tests are failing.
I tried resetting the jest function. But not working.
Are there any other ways to try?
Thanks in advance :)