Skip to content

Unit test

Test routes with Web Standard Request and Response objects. You don’t need to open a port for a handler test.

Elysia provides the Elysia.handle method, which accepts a Web Standard Request and returns a promise of a Response, simulating an HTTP Request.

Bun includes a built-in test runner that offers a Jest-like API through the bun:test module, facilitating the creation of unit tests.

Create test/index.test.ts in the root of the project directory with the following:

test/index.test.ts
import { describe, expect, it } from 'bun:test'
import { Elysia } from 'elysia'
describe('Elysia', () => {
it('returns a response', async () => {
const app = new Elysia().get('/', () => 'hi')
const response = await app
.handle(new Request('http://localhost/'))
.then((res) => res.text())
expect(response).toBe('hi')
})
})

Then we can perform tests by running bun test.

Terminal window
bun test

Pass an absolute URL to new Request(). A relative path such as /user is not enough.

We can also use other testing libraries like Jest to create Elysia unit tests.

We may use Eden Treaty to create an end-to-end type safety test for an Elysia server as follows:

test/index.test.ts
import { describe, expect, it } from 'bun:test'
import { Elysia } from 'elysia'
import { treaty } from '@elysia/eden'
const app = new Elysia().get('/hello', 'hi')
const api = treaty(app)
describe('Elysia', () => {
it('returns a response', async () => {
const { data, error } = await api.hello.get()
expect(error).toBeNull()
expect(data).toBe('hi')
})
})

See Eden Treaty Unit Test for setup and more information.

Type to search the documentation.

    Up arrowDown arrow to navigateEnter to selectEscape to close