DEV Community

Discussion on: When should I (not) use mocks in testing?

Collapse
 
pke profile image
Philipp Kursawe

There would be no need for mocks for the getTimestamp function if it would allow to hand in the date.
Impure functions are always harder to test.

test('returns the formatted timestamp', () => {
  expect(getTimestamp(new Date('01 Jan 1970 14:32:19 GMT'))).toEqual('14:32:19')
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kettanaito profile image
Artem Zakharchenko

Undoubtedly. This example's purpose isn't to bring an exact implementation to the light, but to show that there may be small pieces of logic that depend on side effects. Perhaps you see a better example to this?

Collapse
 
kettanaito profile image
Artem Zakharchenko • Edited

The getTimestamp modification you suggest also produces a different function. It converts any given date into a timestamp. Had I a requirement to use it to print only the current date into a timestamp, I'd have to pass it Date.now upon each invocation. Imho, that'd be a good sign that the date belongs in the function itself, given the aforementioned requirements.