You could write a more thorough manual mock for dayjs
, one that has the extend
method, but then you're coupling your tests to a 3rd party interface. "Don't mock what you don't own" - you'll end up having to recreate more and more of the dayjs
interface in your mock, and then if that interface changes your tests will continue to pass but your code will be broken. Or if you decide to swap to a different time library, you have to rewrite all of your tests to manually mock the new interface.
Instead, treat time as a dependency. Have your own function, in your own module, that simply provides the current time as a Date
object:
export const howSoonIsNow = () => new Date();
Then, when you need to create a dayjs
object, do so from that (dayjs()
is equivalent to dayjs(new Date())
per the docs):
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { howSoonIsNow } from './path/to/noTimeLikeThePresent';
dayjs.extend(utc);
dayjs(howSoonIsNow()).add(15, 'minute');
Now in your test you can swap out something you actually own, and not have to interfere with dayjs
at all:
import { howSoonIsNow } from './path/to/noTimeLikeThePresent';
jest.mock('./path/to/noTimeLikeThePresent');
howSoonIsNow.mockReturnValue(new Date(2020, 8, 12));
Now if a new version of dayjs
changes in a way that breaks your use of it, your tests will fail and tell you as much. Or if you swap to a different time library you don't have to rewrite all of your tests, so you can be confident you've swapped over correctly.
Also FWIW I don't rate snapshot testing in general - it just becomes change detection, failing for irrelevant changes and encouraging people to ignore the test results and blindly recreate the snapshots if anything fails. Test based on the behaviour you want to see from your components.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…