Test context

Test context

An instance of the TestContext class is shared with all the tests and the test hooks. Japa creates an isolated instance of TestContext for every test. Therefore, you can add custom properties without worrying about it leaking to other tests.

Based on your installed plugins, you may access different properties via the ctx object.

Access context inside a test
import { test } from '@japa/runner'
test('add two numbers', (ctx) => {
console.log(ctx)
})
Access context inside hooks
import { test } from '@japa/runner'
test.group('Maths.add', (group) => {
group.each.setup(($test) => {
console.log($test.context)
})
group.each.teardown(($test) => {
console.log($test.context)
})
test('add two number', (ctx) => {
console.log(ctx)
})
})

TestContext properties

Following is the list of properties you may access through the TestContext class.

assert

The assert property is shared by the @japa/assert plugin.

expect

The expect property is shared by the @japa/expect plugin.

fs

The fs property is shared by the @japa/file-system plugin.

expectTypeOf

The expectTypeOf property is shared by the @japa/expect-type plugin.

client

The client property is shared by the @japa/api-client plugin.

browser, browserContext, visit

The browser-related properties are shared by the @japa/browser-client plugin.

cleanup

The cleanup function can define a cleanup hook from within the test callback. Learn more.

Extending TestContext

You can add custom properties to the TestContext class using macros and getters. Macros and getters offer an API to add properties to the prototype of a class. You can think of them as Syntactic sugar for Object.defineProperty. Under the hood, we use macroable package, and you can refer to its README for an in-depth technical explanation.

You can define custom properties inside the Japa entry point file (i.e., bin/test(.js|.ts)).

bin/test.js
import { TestContext } from '@japa/runner/core'
TestContext.macro('sleep', function (milliseconds) {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds)
})
})

Once you have defined the sleep method, you can access it as follows within your tests.

test('add two numbers', ({ sleep }) => {
await sleep(4000)
})

Defining TypeScript types

If you use TypeScript, you must notify its compiler about the newly added property using declaration merging.

Again, you may write the following code within the Japa entry point file.

declare module '@japa/runner/core' {
interface TestContext {
sleep(milliseconds: number): Promise<void>
}
}