github avajs/ava v8.6.0

one hour ago

Support setup-function teardowns and disposable resources

By @novemberborn in #3524

Extends t.teardown() to accept (async) disposables.

Allows t.teardown() to be used in before and beforeEach setup functions. The teardowns are invoked after the corresponding test postconditions, including .always variants.

For these teardowns, the execution context t of the setup function is rebound to the teardown invocation. This means assertions, logs, plans and timeouts affect the teardown rather than the completed setup function.

after and afterEach are now presented as postconditions. Any resources created during setup (before and beforeEach) should be cleaned up using a teardown, not a postcondition.

import {once} from 'node:events';
import {createServer} from 'node:http';
import test from 'ava';

test.beforeEach(async t => {
  let requests = 0;
  const server = createServer((request, response) => {
    requests++;
    response.end('Hello!');
  });

  t.teardown(server); // Closes the server via Symbol.asyncDispose.
  await once(server.listen(0, '127.0.0.1'), 'listening');

  t.context = {server, getRequests: () => requests};
});

test('responds to a request', async t => {
  const {port} = t.context.server.address();
  const response = await fetch(`http://127.0.0.1:${port}`);

  t.is(await response.text(), 'Hello!');
});

test.afterEach('handled one request', t => {
  t.is(t.context.getRequests(), 1); // The server is still available here.
});

And a teardown using t:

test.beforeEach(async t => {
  let requests = 0;
  const server = createServer((request, response) => {
    requests++;
    response.end('Hello!');
  });

  t.teardown(async () => {
    await server[Symbol.asyncDispose]();
    t.log('closed server'); // Logged under the teardown.
  });
  await once(server.listen(0, '127.0.0.1'), 'listening');

  t.context = {server, getRequests: () => requests};
});

The HookSkipFn is deprecated in favor of LifecycleSkipFn.

Other Changes

Full Changelog: v8.5.0...v8.6.0

Don't miss a new ava release

NewReleases is sending notifications on new releases.