@journyio/clock
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

journy.io

Clock

npm npm downloads

Consume time as a service.

💾 Installation

You can use your package manager (npm or yarn) to install:

npm install --save @journyio/clock

or

yarn add @journyio/clock

This package depends on moment/luxon. If you already have another datetime library installed in your project, we advise you to fork this package.

We don't recommend consuming this package in plain JavaScript (to be able to use interfaces).

🔌 Getting started

First, read this blogpost to understand the reasoning behind this approach.

Let's say we have a class that creates a user:

import { DateTime } from "luxon";
import { Clock } from "@journyio/clock";

class User {
  constructor(/* ... */ private readonly createdAt: DateTime) {}

  getCreatedAt() {
    return this.createdAt;
  }
}

class UserService {
  constructor(private readonly clock: Clock) {}

  create(/* ... */): User {
    return new User(
      /* ... */
      this.clock.getUTCTime()
    );
  }
}

In our tests we can use ClockFixed to control the current time:

import { ClockFixed } from "@journyio/clock";

const now = DateTime.utc();
const clock = new ClockFixed(now);
const userService = new UserService(clock);
const user = userService.create(/* ... */);

expect(user.getCreatedAt()).toEqual(now);

In our normal code we can use ClockSystem:

import { ClockSystem } from "@journyio/clock";

const userService = new UserService(new ClockSystem());

By depending on Clock we can consume time as a service (so that we're in control of time). Normally we would need to rely on magic or use setTimeout to test code that uses the current time.

💯 Tests

To run the tests:

npm run test

Package Sidebar

Install

npm i @journyio/clock

Weekly Downloads

2

Version

2.0.0

License

MIT

Unpacked Size

6.8 kB

Total Files

11

Last publish

Collaborators

  • hansjourny
  • manujourny