Disposable mock dates for NodeJS using mockdate
Disposable mock dates for NodeJS using mockdate.
Using this correctly with NodeJS requires TypeScript 5.2 as well as a
polyfill (see example usage below). I wouldn't recommend it for
production code yet, since it's still in beta an a lot of important
tooling (prettier, eslint, etc) doesn't support it yet.
1. Install TypeScript 5.2 (currently yarn add -D typescript@beta or
npm i -D typescript@beta).
2. Install this package (yarn add disposable-mock-date or npm i disposable-mock-date).
Here's an example of using it in a jest test.
``ts
import mockDate from "disposable-mock-date";
// Either add this polyfill yourself, or use something like core-js
// See https://devblogs.microsoft.com/typescript/announcing-typescript-5-2-beta/
// @ts-expect-error
Symbol.dispose ??= Symbol("Symbol.dispose");
describe(('how to use the function')=>{
it("is always good to have predicable inputs", () => {
using _ = disposableMockDate('2020-02-02');
expect(new Date()).toStrictEqual(new Date('2020-02-02'))
});
it("will not work here", () => {
// new Date() will be set back to the current time
expect(new Date()).toStrictEqual(new Date('2020-02-02'))
});
});
``
- ESM support
- Fix prettier (TypeScript 5.2 support in progress: https://github.com/prettier/prettier/issues/15004)
- Fix eslint (TypeScript 5.2 support in progress: https://github.com/typescript-eslint/typescript-eslint/issues/7155)