Skip to content

Latest commit

 

History

History
48 lines (33 loc) · 2.44 KB

File metadata and controls

48 lines (33 loc) · 2.44 KB

Endpoint testing

Translations: Español, Français, Italiano, 日本語, Português, Русский, 简体中文

Open in StackBlitz

AVA doesn't have a built-in method for testing endpoints, but you can use any HTTP client of your choosing, for example ky. You'll also need to start an HTTP server, preferably on a unique port so that you can run tests in parallel. For that we recommend async-listen.

Since tests run concurrently, it's best to create a fresh server instance at least for each test file, but perhaps even for each test. This can be accomplished with test.before() and test.beforeEach() hooks and t.context. If you start your server using a test.before() hook you should make sure to execute your tests serially.

Check out the example below:

import {createServer} from 'node:http';

import {listen} from 'async-listen';
import test from 'ava';
import ky, {HTTPError} from 'ky';

import app from './app.js';

test.before(async t => {
	t.context.server = createServer(app);
	t.context.prefixUrl = await listen(t.context.server);
});

test.after.always(t => {
	t.context.server.close();
});

test.serial('get /user', async t => {
	const {email} = await ky('user', {prefixUrl: t.context.prefixUrl}).json();

	t.is(email, 'ava@rocks.com');
});

test.serial('404', async t => {
	await t.throwsAsync(
		ky('password', {prefixUrl: t.context.prefixUrl}),
		{message: /Request failed with status code 404 Not Found/, instanceOf: HTTPError},
	);
});

Other libraries you may find useful: