Hooks
Loading "Handle Test Side Effects (🏁 solution)"
Handle Test Side Effects (🏁 solution)
Run locally for transcripts
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()
}
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'),
})
})
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
})