@shopify/jest-dom-mocks
Version:
Jest mocking utilities for working with the DOM
40 lines (38 loc) • 931 B
JavaScript
class Clock {
constructor() {
this.isUsingMockClock = false;
}
mock(now = Date.now()) {
if (this.isUsingMockClock) {
throw new Error('The clock is already mocked, but you tried to mock it again.');
}
jest.useFakeTimers({
now
});
this.isUsingMockClock = true;
}
restore() {
if (!this.isUsingMockClock) {
throw new Error('The clock is already real, but you tried to restore it again.');
}
jest.useRealTimers();
this.isUsingMockClock = false;
}
isMocked() {
return this.isUsingMockClock;
}
tick(time) {
this.ensureClockIsMocked();
jest.advanceTimersByTime(time);
}
setTime(time) {
this.ensureClockIsMocked();
jest.setSystemTime(time);
}
ensureClockIsMocked() {
if (!this.isUsingMockClock) {
throw new Error('You must call clock.mock() before interacting with the mock clock.');
}
}
}
export { Clock as default };