Skip to content

document an approach for referencing 'now' #3323

Description

@henryw374

In the javadoc for java.time InstantSource it says:

The primary purpose of this abstraction is to allow alternate instant sources to be plugged in as and when required. Applications use an object to obtain the current time rather than a static method. This can simplify testing.

The benefits would apply in Javascript as well of course and I have found it trivial to treat Temporal.Now as an interface, instances of which can become a parameter to anywhere in code that needs to reference the current date or zone. I can find no mentions of this in the Temporal naming or documentation. Could this approach be considered for an entry in the cookbook?

To explain what I mean, here is some production/non-test code

function doSomethingReferencingNow(clock: typeof Temporal.Now) {
    // The following line could have been `Temporal.Now.plainDateISO()` but
    // that would make testing difficult
    // assume real code would do something more complex ofc
  return clock.plainDateISO();
}

// ... at the point of (system) initiation
const clock = Temporal.Now;
// ... anywhere in the code that needs 'now' is passed a reference to the `clock`
 doSomethingReferencingNow(clock);

When testing doSomethingReferencingNow

// Clock is pretty much a one-liner with the same shape as Temporal.Now
import { Clock } from '@widdindustries/temporal-test-clock';

let changingTime = Temporal.Instant.from('2020-01-02T03:04:05.123456789Z')
const doesAnythingYouWantClock = new Clock(
 () => changingTime,
 () => Temporal.Now.timeZoneId()
);
const initialResult = doSomethingReferencingNow(doesAnythingYouWantClock);
//... simulate passing of time for example
const duration = Temporal.Duration.from("PT1S");
changingTime = changingTime.add(duration);
const subsequentResult = doSomethingReferencingNow(doesAnythingYouWantClock);
// do assertions as required etc

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions