Test Files
Loading "Move Tests Into Modules (🏁 solution)"
Run locally for transcripts
I start by creating a new
greet.test.ts
file and moving only the test(...)
blocks there.test('returns a greeting message for the given name', () => {
expect(greet('John')).toBe('Hello, John!')
})
test('returns a congratulation message for the given name', () => {
expect(congratulate('Sarah')).toBe('Congrats, Sarah!')
})
.spec.ts
or .test.ts
, or both?If I try to run test test file now, it will exit on undefined
greet()
and congratulation()
functions because they are neither defined nor imported from anywhere.So I go and export those functions from the
greet.ts
module:export function greet(name: string) {
return `Hello, ${name}!`
}
export function congratulate(name: string) {
return `Congrats, ${name}!`
}
And import them in the test file:
import { greet, congratulate } from './greet.js'
Next, I want to make the
test()
and expect()
functions available globally. Every test will be using those, so there's no need to explicitly import them every time.Next, I create a
setup.ts
file where I start by describing the test()
and expect()
functions in TypeScript. I add them to the global
namespace to let TypeScript know those functions will be available globally, and that we don't have to import them.interface Assertions {
toBe(expected: unknown): void
}
declare global {
var expect: (actual: unknown) => Assertions
var test: (title: string, callback: () => void) => void
}
Then, I move the existing
test()
and expect()
functions directly to the globalThis
object to expose them globally on runtime and also benefit from the type inference since they are now fully annotated!globalThis.expect = function (actual) {
return {
toBe(expected: unknown) {
if (actual !== expected) {
throw new Error(`Expected ${actual} to equal to ${expected}`)
}
},
}
}
globalThis.test = function (title, callback) {
try {
callback()
console.log(`✓ ${title}`)
} catch (error) {
console.error(`✗ ${title}`)
console.error(error, '\n')
}
}
All that remains is to verify that the tests are running correctly.
npx tsx --import ./setup.ts greet.test.ts
I am using the--import
option in Node.js to load thesetup.ts
module before runninggreet.test.ts
. This makes thetest()
andexpect()
functions globally available in the test's runtime.