hands-clappingUsage example

Injecting the Clock

import { Injectable } from '@nestjs/common';
import { IClock, Clock } from '@nestjstools/clock';

@Injectable()
export class SubscriptionService {
  constructor(@Clock() private readonly clock: IClock) {}

  isSubscriptionActive(startDate: Date, durationDays: number): boolean {
    const now = this.clock.now();

    const endDate = new Date(startDate);
    endDate.setDate(endDate.getDate() + durationDays);

    return now < endDate;
  }
}

Notice:

  • No new Date() inside domain logic

  • Time is injected

  • Fully testable


🧪 Testing

Override the clock in tests:

Deterministic. Predictable. Clean.

Last updated

Was this helpful?