Skip to content
Permalink
master
Go to file
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
13 contributors

Users who have contributed to this file

@sindresorhus @forresst @timgates42 @goto-bus-stop @paulrobertlloyd @mattkrick @silvenon @ydaniv @zhaozhiming @jfmengels @charbelrami @tryzniak
36 lines (26 sloc) 2.06 KB

Endpoint testing

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

AVA doesn't have a built-in method for testing endpoints, but you can use any HTTP client of your choosing, for example got. 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 test-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:

const http = require('http');
const test = require('ava');
const got = require('got');
const listen = require('test-listen');
const app = require('../app');

test.before(async t => {
	t.context.server = http.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 got('user', {prefixUrl: t.context.prefixUrl}).json();
	t.is(email, 'ava@rocks.com');
});

Other libraries you may find useful: