Hooks

First, I add the beforeAll() and afterAll() function declarations to the global namespace in TypeScript:
interface Assertions {
	toBe(expected: unknown): void
}

declare global {
	var expect: (actual: unknown) => Assertions
	var test: (title: string, callback: () => void) => void
	var beforeAll: (callback: () => void) => void
	var afterAll: (callback: () => void) => void
}
Then, I implement the beforeAll() function, which invokes the given callback immediately.
globalThis.beforeAll = function (callback) {
	callback()
}
Here, I'm relying on the fact that the beforeAll() function will be called before any individual tests. Actual testing frameworks usually have a runner responsible for internally orchestrating hooks and tests regardless of the invocation order.
The afterAll function will be a bit different. To invoke the callback once the tests are done, I will utilize the beforeExit event of a Node.js process to let me know when the test run is about to exit.
globalThis.afterAll = function (callback) {
	process.on('beforeExit', () => {
		callback()
	})
}
Then, I go to the greet.test.ts and add the beforeAll() hook that patches the global Date constructor and uses the stored OriginalDate class to create a fixed date.
const OriginalDate = globalThis.Date

beforeAll(() => {
	globalThis.Date = new Proxy(globalThis.Date, {
		construct: () => new OriginalDate('2024-01-01'),
	})
})
I recommend providing an entire UTC date, including an explicit timezone, as the value of the mocked date to have a resilient test setup: new OriginalDate('2024-01-01 00:00:00.000Z')
Similarly, I make sure to clean up this Date mock in the afterAll() hook:
afterAll(() => {
	globalThis.Date = OriginalDate
})
Remember the rule of clean hooks: have a cleanup for each side effect in your setup (e.g. spawn a server → close the server; patch a global → restore the global).

Please set the playground first

Loading "Hooks"
Loading "Hooks"

Access Denied

You must login or register for the workshop to view and run the tests.

Check out this video to see how the test tab works.