Commit 08ea45a for jssip.net

commit 08ea45a4d3282fcf69e86dde55268a0d0023bada
Author: José Luis Millán <jmillan@aliax.net>
Date:   Tue Dec 1 12:57:24 2026 +0100

    Enhance tests (#1000)

diff --git a/.gitignore b/.gitignore
index 8d4f7a5..ab7f54a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,6 @@
 /docs
 /coverage
 /.cache
+
+## Temporal
+/examples
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f905457..5225a62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@
 - Subscriber: Fix, accept the initial NOTIFY arriving before the 2xx response to the SUBSCRIBE (#993). Thanks to @hyponex and @AhmedElbashier for reporting.
 - Registrator: Add 'registrationRefreshed' event and report the granted expiry in 'registered' (#994). Thanks to @hyponex for reporting.
 - UA: Fix, accept incoming requests whose Request-URI is a GRUU granted by the registrar (#844). Thanks to @mtryfoss for reporting.
+- UA: stop() closes the transport as soon as the pending transactions are done, instead of always waiting 2 seconds.

 ### 3.13.9

diff --git a/npm-scripts.mjs b/npm-scripts.mjs
index a2d3a10..9c6ea33 100644
--- a/npm-scripts.mjs
+++ b/npm-scripts.mjs
@@ -125,6 +125,9 @@ function lint(fix = false) {
 function test() {
 	logInfo('test()');

+	// NOTE: ts-jest does not type check (`isolatedModules`), so do it here.
+	executeCmd('tsc --noEmit');
+
 	executeCmd(`jest --silent false --detectOpenHandles ${taskArgs}`);
 }

@@ -203,8 +206,12 @@ function buildTypescript() {

 	deleteLib();

+	// Type check everything, tests included, without generating anything.
+	executeCmd('tsc --noEmit');
+
 	// Generate .js CommonJS files in lib/.
-	executeCmd(`tsc ${taskArgs}`);
+	// NOTE: tsconfig.build.json excludes the tests, so they don't end in lib/.
+	executeCmd(`tsc -p tsconfig.build.json ${taskArgs}`);

 	// Copy manual .d.ts files to lib/ until code is moved to TS and declaration files
 	// are automatically created.
diff --git a/src/Grammar.d.ts b/src/Grammar.d.ts
index eab4429..a6abd86 100644
--- a/src/Grammar.d.ts
+++ b/src/Grammar.d.ts
@@ -71,6 +71,17 @@ export type EventHeader = {
 	params?: GenericParams;
 };

+/**
+ * Result of the `Subscription_State` start rule.
+ */
+export type SubscriptionStateHeader = {
+	state: string;
+	reason?: string;
+	expires?: number;
+	retry_after?: number;
+	params?: GenericParams;
+};
+
 /**
  * Result of the `Refer_To` start rule.
  */
diff --git a/src/UA.d.ts b/src/UA.d.ts
index 0938f7a..16c0f3f 100644
--- a/src/UA.d.ts
+++ b/src/UA.d.ts
@@ -19,6 +19,8 @@ import { Notifier } from './Notifier';
 import { Subscriber } from './Subscriber';
 import URI = require('./URI');
 import { causes } from './Constants';
+import { Configuration } from './Configuration';
+import { Transport } from './Transport';

 export interface UnRegisterOptions {
 	all?: boolean;
@@ -184,7 +186,7 @@ export interface UAContactOptions {
 export interface UAContact {
 	pub_gruu?: string;
 	temp_gruu?: string;
-	uri?: string;
+	uri: URI;

 	toString(options?: UAContactOptions): string;
 }
@@ -245,6 +247,10 @@ export class UA extends EventEmitter {

 	get contact(): UAContact;

+	get configuration(): Configuration;
+
+	get transport(): Transport;
+
 	start(): void;

 	stop(): void;
diff --git a/src/UA.js b/src/UA.js
index d96f046..31dc25f 100644
--- a/src/UA.js
+++ b/src/UA.js
@@ -21,6 +21,12 @@ const config = require('./Configuration');

 const logger = new Logger('UA');

+/* How long stop() waits for the transactions pending at that moment, so that
+ * the requests it sends (un-REGISTER, BYE, un-SUBSCRIBE) get a chance to be
+ * answered before the transport goes away.
+ */
+const CLOSE_TIMEOUT = 2000;
+
 const C = {
 	// UA status codes.
 	STATUS_INIT: 0,
@@ -317,9 +323,6 @@ module.exports = class UA extends EventEmitter {
 		// Close registrator.
 		this._registrator.close();

-		// If there are session wait a bit so CANCEL/BYE can be sent and their responses received.
-		const num_sessions = Object.keys(this._sessions).length;
-
 		// Run  _terminate_ on every Session.
 		for (const session in this._sessions) {
 			if (Object.prototype.hasOwnProperty.call(this._sessions, session)) {
@@ -351,20 +354,12 @@ module.exports = class UA extends EventEmitter {

 		this._status = C.STATUS_USER_CLOSED;

-		const num_transactions =
-			Object.keys(this._transactions.nict).length +
-			Object.keys(this._transactions.nist).length +
-			Object.keys(this._transactions.ict).length +
-			Object.keys(this._transactions.ist).length;
+		/* Give some time for the requests sent above to be answered. _mayClose()
+		 * closes as soon as they are.
+		 */
+		this._closeTimer = setTimeout(() => this._close(), CLOSE_TIMEOUT);

-		if (num_transactions === 0 && num_sessions === 0) {
-			this._transport.disconnect();
-		} else {
-			this._closeTimer = setTimeout(() => {
-				this._closeTimer = null;
-				this._transport.disconnect();
-			}, 2000);
-		}
+		this._mayClose();
 	}

 	/**
@@ -480,6 +475,8 @@ module.exports = class UA extends EventEmitter {
 		this.emit('transactionDestroyed', {
 			transaction,
 		});
+
+		this._mayClose();
 	}

 	/**
@@ -546,6 +543,8 @@ module.exports = class UA extends EventEmitter {
 	 */
 	destroyRTCSession(session) {
 		delete this._sessions[session.id];
+
+		this._mayClose();
 	}

 	/**
@@ -787,6 +786,46 @@ module.exports = class UA extends EventEmitter {
 	// Utils.
 	// =================

+	/**
+	 * Whether the UA has anything left to wait for.
+	 *
+	 * Sessions are looked at besides the transactions because a session sits
+	 * here with none of its own once its dialog is confirmed. Subscribers and
+	 * applicants are not: each is destroyed while handling the response to its
+	 * last request, a tick before the transaction that carried it.
+	 */
+	_isIdle() {
+		return (
+			Object.keys(this._sessions).length === 0 &&
+			Object.keys(this._transactions.nict).length === 0 &&
+			Object.keys(this._transactions.nist).length === 0 &&
+			Object.keys(this._transactions.ict).length === 0 &&
+			Object.keys(this._transactions.ist).length === 0
+		);
+	}
+
+	/**
+	 * Ends the shutdown begun by stop().
+	 */
+	_close() {
+		this._closeTimer = null;
+		this._transport.disconnect();
+	}
+
+	/**
+	 * Closes a stopping UA as soon as what was pending when it was stopped is
+	 * done with, instead of waiting for the whole CLOSE_TIMEOUT.
+	 */
+	_mayClose() {
+		// A close timer is only pending while the UA is stopping.
+		if (this._closeTimer === null || !this._isIdle()) {
+			return;
+		}
+
+		clearTimeout(this._closeTimer);
+		this._close();
+	}
+
 	/**
 	 * Whether the Request-URI of an incoming request addresses this UA.
 	 */
diff --git a/src/test/include/LoopSocket.ts b/src/test/include/LoopSocket.ts
index daa0e9c..65573c0 100644
--- a/src/test/include/LoopSocket.ts
+++ b/src/test/include/LoopSocket.ts
@@ -1,16 +1,11 @@
-// LoopSocket send message itself.
-// Used P2P logic: message call-id is modified in each leg.
-// LoopSocket.pair() links two sockets, so that two UAs talk to each other.
+// LoopSocket sends every message to its peer socket, so that two UAs talk to
+// each other. Unpaired, it talks to itself, with the Call-ID modified on each
+// leg so that the single UA sees two distinct dialogs.

-import type { Socket } from '../../Socket';
-
-export default class LoopSocket implements Socket {
-	url = 'ws://localhost:12345';
-	via_transport = 'WS';
-	sip_uri = 'sip:localhost:12345;transport=ws';
-
-	private peer: LoopSocket = this;
+import TestSocket from './TestSocket';

+export default class LoopSocket extends TestSocket {
+	// LoopSocket.pair() links two sockets, so that two UAs talk to each other.
 	static pair(): [LoopSocket, LoopSocket] {
 		const a = new LoopSocket();
 		const b = new LoopSocket();
@@ -21,39 +16,20 @@ export default class LoopSocket implements Socket {
 		return [a, b];
 	}

-	connect(): void {
-		setTimeout(() => {
-			this.onconnect();
-		}, 0);
-	}
-
-	disconnect(): void {}
-
-	send(message: string): boolean {
-		const new_message = this.modifyCallId(message);
-
-		setTimeout(() => {
-			this.peer.ondata(new_message);
-		}, 0);
+	private peer: LoopSocket = this;

-		return true;
+	protected override onRequest(message: string): void {
+		this.forward(message);
 	}

-	isConnected(): boolean {
-		return true;
+	protected override onResponse(message: string): void {
+		this.forward(message);
 	}

-	isConnecting(): boolean {
-		return false;
+	private forward(message: string): void {
+		this.peer.receive(this.modifyCallId(message));
 	}

-	onconnect(): void {}
-
-	ondisconnect(): void {}
-
-	// eslint-disable-next-line @typescript-eslint/no-unused-vars
-	ondata<T>(_event: T): void {}
-
 	// Call-ID: add or drop word '_second'.
 	private modifyCallId(message: string): string {
 		const begin = message.indexOf('Call-ID');
diff --git a/src/test/include/RegistrarSocket.ts b/src/test/include/RegistrarSocket.ts
new file mode 100644
index 0000000..21d1b07
--- /dev/null
+++ b/src/test/include/RegistrarSocket.ts
@@ -0,0 +1,55 @@
+import TestSocket from './TestSocket';
+import { buildResponse, header, method } from './sipMessage';
+
+export type RegistrarOptions = {
+	// The lifetime granted, when it is not the one the UA asked for.
+	expires?: number;
+	pubGruu?: string;
+	tempGruu?: string;
+};
+
+/**
+ * A registrar that accepts every REGISTER, echoing the Contact back with the
+ * parameters it grants (RFC 3261, Section 10.3).
+ */
+export default class RegistrarSocket extends TestSocket {
+	// Set to false to leave the following REGISTER unanswered.
+	answering = true;
+
+	constructor(private readonly granted: RegistrarOptions = {}) {
+		super();
+	}
+
+	protected override onRequest(request: string): void {
+		if (method(request) !== 'REGISTER' || !this.answering) {
+			return;
+		}
+
+		this.receive(
+			buildResponse(request, 200, {
+				toTag: 'registrartag',
+				extraHeaders: [`Contact: ${this.contact(request)}`],
+			})
+		);
+	}
+
+	private contact(request: string): string {
+		const { expires, pubGruu, tempGruu } = this.granted;
+
+		let contact = header(request, 'Contact');
+
+		if (expires !== undefined) {
+			contact = contact.replace(/;expires=\d+/, `;expires=${expires}`);
+		}
+
+		if (pubGruu) {
+			contact += `;pub-gruu="${pubGruu}"`;
+		}
+
+		if (tempGruu) {
+			contact += `;temp-gruu="${tempGruu}"`;
+		}
+
+		return contact;
+	}
+}
diff --git a/src/test/include/TestSocket.ts b/src/test/include/TestSocket.ts
new file mode 100644
index 0000000..1bdc5e0
--- /dev/null
+++ b/src/test/include/TestSocket.ts
@@ -0,0 +1,106 @@
+// Base for the sockets that play the remote peer in tests.
+
+import type { Socket } from '../../Socket';
+import { header, isRequest, method, status } from './sipMessage';
+
+/**
+ * Implements the whole Socket interface, records every message the UA writes
+ * and feeds messages back into it, so that a suite only has to say what the
+ * peer answers.
+ *
+ * Subclasses react to what the UA sends by overriding onRequest() and
+ * onResponse(), and reply through receive().
+ */
+export default abstract class TestSocket implements Socket {
+	url = 'ws://localhost:12345';
+	via_transport = 'WS';
+	sip_uri = 'sip:localhost:12345;transport=ws';
+
+	// Every message the UA has written, in order.
+	readonly sent: string[] = [];
+
+	// Delivery instant of the last message handed to the UA. Kept monotonic so
+	// that messages reach the UA in the order they were given.
+	private tick = 0;
+
+	connect(): void {
+		setTimeout(() => this.onconnect(), 0);
+	}
+
+	disconnect(): void {}
+
+	isConnected(): boolean {
+		return true;
+	}
+
+	isConnecting(): boolean {
+		return false;
+	}
+
+	send(message: string): boolean {
+		this.sent.push(message);
+
+		if (isRequest(message)) {
+			this.onRequest?.(message);
+		} else {
+			this.onResponse?.(message);
+		}
+
+		return true;
+	}
+
+	onconnect(): void {}
+
+	ondisconnect(): void {}
+
+	// eslint-disable-next-line @typescript-eslint/no-unused-vars
+	ondata(_data: string | ArrayBuffer): void {}
+
+	/**
+	 * Hands the messages to the UA, asynchronously and in the given order.
+	 */
+	receive(...messages: string[]): void {
+		for (const message of messages) {
+			setTimeout(() => this.ondata(message), ++this.tick);
+		}
+	}
+
+	/**
+	 * The requests the UA sent, of the given method only if one is given.
+	 */
+	requests(name?: string): string[] {
+		return this.sent.filter(
+			message => isRequest(message) && (!name || method(message) === name)
+		);
+	}
+
+	/**
+	 * The responses the UA sent, to the given method only if one is given.
+	 */
+	responses(name?: string): string[] {
+		return this.sent.filter(
+			message => !isRequest(message) && (!name || method(message) === name)
+		);
+	}
+
+	/**
+	 * Status code the UA answered the request with the given Call-ID with.
+	 */
+	statusFor(callId: string): number | undefined {
+		const response = this.responses().find(
+			message => header(message, 'Call-ID') === callId
+		);
+
+		return response ? status(response) : undefined;
+	}
+
+	/**
+	 * Called for every request the UA sends.
+	 */
+	protected onRequest?(request: string): void;
+
+	/**
+	 * Called for every response the UA sends.
+	 */
+	protected onResponse?(response: string): void;
+}
diff --git a/src/test/include/consts.ts b/src/test/include/consts.ts
index 5e3a138..16c3df2 100644
--- a/src/test/include/consts.ts
+++ b/src/test/include/consts.ts
@@ -1,29 +1,41 @@
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export const SOCKET_DESCRIPTION: Record<string, any> = {
+import type { UAConfiguration } from '../../UA';
+
+export const SOCKET_DESCRIPTION = {
 	via_transport: 'WS',
 	sip_uri: 'sip:localhost:12345;transport=ws',
 	url: 'ws://localhost:12345',
 };

-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export const UA_CONFIGURATION: Record<string, any> = {
-	uri: 'sip:f%61keUA@jssip.net',
-	password: '1234ññññ',
-	display_name: 'Fake UA ð→€ł !!!',
-	authorization_user: 'fakeUA',
-	instance_id: 'uuid:8f1fa16a-1165-4a96-8341-785b1ef24f12',
-	registrar_server: 'registrar.jssip.NET:6060;TRansport=TCP',
-	register_expires: 600,
-	register: false,
-	connection_recovery_min_interval: 2,
-	connection_recovery_max_interval: 30,
-	use_preloaded_route: true,
-	no_answer_timeout: 60000,
-	session_timers: true,
-};
+/**
+ * What the application configures. A function, so that each test gets its own
+ * object to hand to a UA, which mutates the configuration it is given.
+ */
+export function uaConfiguration(
+	overrides: Partial<UAConfiguration> & Pick<UAConfiguration, 'sockets'>
+): UAConfiguration {
+	return {
+		uri: 'sip:f%61keUA@jssip.net',
+		password: '1234ññññ',
+		display_name: 'Fake UA ð→€ł !!!',
+		authorization_user: 'fakeUA',
+		instance_id: 'uuid:8f1fa16a-1165-4a96-8341-785b1ef24f12',
+		registrar_server: 'registrar.jssip.NET:6060;TRansport=TCP',
+		register_expires: 600,
+		register: false,
+		connection_recovery_min_interval: 2,
+		connection_recovery_max_interval: 30,
+		use_preloaded_route: true,
+		no_answer_timeout: 60000,
+		session_timers: true,
+		...overrides,
+	};
+}

-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export const UA_CONFIGURATION_AFTER_START: Record<string, any> = {
+/**
+ * What the UA makes of the configuration above once started. Values the UA
+ * turns into objects are compared as strings.
+ */
+export const UA_CONFIGURATION_AFTER_START = {
 	uri: 'sip:fakeUA@jssip.net',
 	password: '1234ññññ',
 	display_name: 'Fake UA ð→€ł !!!',
@@ -37,18 +49,8 @@ export const UA_CONFIGURATION_AFTER_START: Record<string, any> = {
 	session_timers: true,
 };

-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export const UA_TRANSPORT_AFTER_START: Record<string, any> = {
-	sockets: [
-		{
-			socket: {
-				via_transport: 'WS',
-				sip_uri: 'sip:localhost:12345;transport=ws',
-				url: 'ws://localhost:12345',
-			},
-			weight: 0,
-		},
-	],
+export const UA_TRANSPORT_AFTER_START = {
+	sockets: [{ socket: SOCKET_DESCRIPTION, weight: 0 }],
 	recovery_options: {
 		min_interval: 2,
 		max_interval: 30,
diff --git a/src/test/include/expect.ts b/src/test/include/expect.ts
new file mode 100644
index 0000000..c6936c1
--- /dev/null
+++ b/src/test/include/expect.ts
@@ -0,0 +1,8 @@
+/**
+ * Fails unless the value is neither undefined nor null, and narrows it for the
+ * rest of the test. Jest's own matchers cannot narrow.
+ */
+export function expectDefined<T>(value: T): asserts value is NonNullable<T> {
+	expect(value).not.toBeUndefined();
+	expect(value).not.toBeNull();
+}
diff --git a/src/test/include/sipMessage.ts b/src/test/include/sipMessage.ts
new file mode 100644
index 0000000..89f2105
--- /dev/null
+++ b/src/test/include/sipMessage.ts
@@ -0,0 +1,189 @@
+// Reading and writing SIP messages in their on-the-wire form, so that suites
+// playing a remote peer don't have to assemble them by hand.
+//
+// The library's own `SIPMessage` covers the parsed form; these helpers work on
+// the text a socket carries.
+
+import { REASON_PHRASE } from '../../Constants';
+
+const CRLF = '\r\n';
+
+/**
+ * First line of a message, without the trailing CRLF.
+ */
+export function startLine(message: string): string {
+	return message.substring(0, message.indexOf(CRLF));
+}
+
+/**
+ * Whether the message is a request rather than a response.
+ */
+export function isRequest(message: string): boolean {
+	return !message.startsWith('SIP/2.0 ');
+}
+
+/**
+ * Method of a request, or the method the response answers to.
+ */
+export function method(message: string): string {
+	return isRequest(message)
+		? startLine(message).split(' ')[0]!
+		: cseq(message).method;
+}
+
+/**
+ * Request-URI of a request.
+ */
+export function ruri(message: string): string {
+	return startLine(message).split(' ')[1]!;
+}
+
+/**
+ * Status code of a response.
+ */
+export function status(message: string): number {
+	return Number(startLine(message).split(' ')[1]);
+}
+
+/**
+ * Values of every header field with the given name, in order of appearance.
+ */
+export function headers(message: string, name: string): string[] {
+	const matches = message.matchAll(new RegExp(`^${name}: *(.*)$`, 'gim'));
+
+	return [...matches].map(match => match[1]!.trim());
+}
+
+/**
+ * Value of the first header field with the given name.
+ */
+export function header(message: string, name: string): string {
+	const value = headers(message, name)[0];
+
+	if (value === undefined) {
+		throw new Error(`no "${name}" header field in message:\n${message}`);
+	}
+
+	return value;
+}
+
+/**
+ * Sequence number and method of the CSeq header field.
+ */
+export function cseq(message: string): { number: number; method: string } {
+	const [number, name] = header(message, 'CSeq').split(' ');
+
+	return { number: Number(number), method: name! };
+}
+
+/**
+ * The 'tag' parameter of a From or To header field value, if any.
+ */
+export function tag(value: string): string | undefined {
+	return /;tag=([^;]+)/i.exec(value)?.[1];
+}
+
+/**
+ * Body of a message.
+ */
+export function body(message: string): string {
+	return message.substring(message.indexOf(CRLF + CRLF) + 2 * CRLF.length);
+}
+
+type Content = {
+	contentType?: string;
+	body?: string;
+};
+
+type Common = Content & {
+	extraHeaders?: string[];
+};
+
+export type ResponseOptions = Common & {
+	// Reason phrase. Defaults to the one RFC 3261 gives for the status code.
+	reason?: string;
+	// Added to the To header field, unless the request already carries a tag.
+	toTag?: string;
+};
+
+export type RequestOptions = Common & {
+	// Defaults to the Via of a fictitious peer, unique per request.
+	via?: string;
+	from: string;
+	to: string;
+	callId: string;
+	cseq: number;
+};
+
+/**
+ * A response to the given request, copying the header fields a UAS must echo
+ * (RFC 3261, Section 8.2.6.2).
+ */
+export function buildResponse(
+	request: string,
+	statusCode: number,
+	options: ResponseOptions = {}
+): string {
+	const to = header(request, 'To');
+	const reason = options.reason ?? REASON_PHRASE[statusCode] ?? '';
+
+	return assemble(
+		`SIP/2.0 ${statusCode} ${reason}`,
+		[
+			...headers(request, 'Via').map(via => `Via: ${via}`),
+			`From: ${header(request, 'From')}`,
+			`To: ${options.toTag && !tag(to) ? `${to};tag=${options.toTag}` : to}`,
+			`Call-ID: ${header(request, 'Call-ID')}`,
+			`CSeq: ${header(request, 'CSeq')}`,
+		],
+		options
+	);
+}
+
+let branch = 0;
+
+/**
+ * A request as a remote peer would send it.
+ */
+export function buildRequest(
+	name: string,
+	requestUri: string,
+	options: RequestOptions
+): string {
+	const via =
+		options.via ?? `SIP/2.0/WS peer.invalid;branch=z9hG4bK.test${++branch}`;
+
+	return assemble(
+		`${name} ${requestUri} SIP/2.0`,
+		[
+			`Via: ${via}`,
+			'Max-Forwards: 69',
+			`From: ${options.from}`,
+			`To: ${options.to}`,
+			`Call-ID: ${options.callId}`,
+			`CSeq: ${options.cseq} ${name}`,
+		],
+		options
+	);
+}
+
+function assemble(
+	firstLine: string,
+	mandatoryFields: string[],
+	options: Common
+): string {
+	const payload = options.body ?? '';
+
+	const fields = [...mandatoryFields, ...(options.extraHeaders ?? [])];
+
+	if (options.contentType) {
+		fields.push(`Content-Type: ${options.contentType}`);
+	}
+
+	/* JsSIP's parser reads the body as data.substr(start, Content-Length), so
+	 * this counts characters rather than bytes.
+	 */
+	fields.push(`Content-Length: ${payload.length}`);
+
+	return [firstLine, ...fields, '', payload].join(CRLF);
+}
diff --git a/src/test/include/ua.ts b/src/test/include/ua.ts
new file mode 100644
index 0000000..292b5b6
--- /dev/null
+++ b/src/test/include/ua.ts
@@ -0,0 +1,53 @@
+// Turns the UA lifecycle events into promises, so that tests read as a
+// sequence of steps instead of nested callbacks.
+
+import type { UA } from '../../UA';
+
+/**
+ * Starts the UA and resolves once it is connected.
+ */
+export function startUA(ua: UA): Promise<void> {
+	const connected = untilConnected(ua);
+
+	ua.start();
+
+	return connected;
+}
+
+/**
+ * Stops the UA and resolves once it is disconnected.
+ */
+export function stopUA(ua: UA): Promise<void> {
+	const disconnected = untilDisconnected(ua);
+
+	ua.stop();
+
+	return disconnected;
+}
+
+/**
+ * Resolves when the UA connects.
+ */
+export function untilConnected(ua: UA): Promise<void> {
+	return new Promise(resolve => {
+		ua.on('connected', () => resolve());
+	});
+}
+
+/**
+ * Resolves when the UA gets its first binding registered.
+ */
+export function untilRegistered(ua: UA): Promise<void> {
+	return new Promise(resolve => {
+		ua.on('registered', () => resolve());
+	});
+}
+
+/**
+ * Resolves when the UA disconnects, whoever stopped it.
+ */
+export function untilDisconnected(ua: UA): Promise<void> {
+	return new Promise(resolve => {
+		ua.on('disconnected', () => resolve());
+	});
+}
diff --git a/src/test/test-JsSIP.ts b/src/test/test-JsSIP.ts
index 3231862..4314628 100644
--- a/src/test/test-JsSIP.ts
+++ b/src/test/test-JsSIP.ts
@@ -1,16 +1,16 @@
 import './include/common';

-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const JsSIP = require('../JsSIP.js');
+import { name, version } from '../JsSIP';
+
 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const pkg = require('../../package.json');

 describe('Properties', () => {
 	test('should have a name property', () => {
-		expect(JsSIP.name).toEqual(pkg.title);
+		expect(name).toEqual(pkg.title);
 	});

 	test('should have a version property', () => {
-		expect(JsSIP.version).toEqual(pkg.version);
+		expect(version).toEqual(pkg.version);
 	});
 });
diff --git a/src/test/test-NameAddrHeader.ts b/src/test/test-NameAddrHeader.ts
index 694fb69..069f990 100644
--- a/src/test/test-NameAddrHeader.ts
+++ b/src/test/test-NameAddrHeader.ts
@@ -1,8 +1,6 @@
 import './include/common';

-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const JsSIP = require('../JsSIP.js');
-const { URI, NameAddrHeader } = JsSIP;
+import { NameAddrHeader, URI } from '../JsSIP';

 describe('NameAddrHeader', () => {
 	test('new NameAddrHeader', () => {
@@ -12,7 +10,7 @@ describe('NameAddrHeader', () => {
 		expect(name.display_name).toBe('Alice æßð');
 		expect(name.toString()).toBe('"Alice æßð" <sip:alice@jssip.net>');

-		name.display_name = null;
+		name.display_name = undefined;
 		expect(name.toString()).toBe('<sip:alice@jssip.net>');

 		name.display_name = 0;
diff --git a/src/test/test-ReferSubscriber.ts b/src/test/test-ReferSubscriber.ts
index 451e8de..1747ef0 100644
--- a/src/test/test-ReferSubscriber.ts
+++ b/src/test/test-ReferSubscriber.ts
@@ -1,7 +1,6 @@
 import './include/common';

-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const ReferSubscriber = require('../RTCSession/ReferSubscriber.js');
+import ReferSubscriber = require('../RTCSession/ReferSubscriber');

 const TARGET = 'sip:bob@example.com';
 const CALL_ID = 'a84b4c76e66710';
diff --git a/src/test/test-Registrator.ts b/src/test/test-Registrator.ts
new file mode 100644
index 0000000..156ab58
--- /dev/null
+++ b/src/test/test-Registrator.ts
@@ -0,0 +1,81 @@
+import { setTimeout as delay } from 'timers/promises';
+
+import './include/common';
+import RegistrarSocket from './include/RegistrarSocket';
+import { startUA, stopUA } from './include/ua';
+
+import { UA } from '../JsSIP';
+import type { RegisteredEvent } from '../UA';
+
+const SUBSCRIBER_URI = 'sip:alice@example.com';
+const CONTACT_URI = 'sip:alice@abcdefabcdef.invalid;transport=ws';
+
+const REQUESTED_EXPIRES = 600;
+
+// MIN_REGISTER_EXPIRES in src/Registrator.js, the floor applied to the refresh
+// timer.
+const MIN_REGISTER_EXPIRES = 10;
+
+type Event = { name: string; expires: number; status: number };
+
+/**
+ * Registers, then refreshes the binding once, the way an application driven by
+ * 'registrationExpiring' does. Resolves on timers rather than on the events
+ * under test, so that a missing event fails the assertion instead of hanging.
+ */
+async function runRegistration(grantedExpires: number): Promise<Event[]> {
+	const socket = new RegistrarSocket({ expires: grantedExpires });
+
+	const ua = new UA({
+		sockets: socket,
+		uri: SUBSCRIBER_URI,
+		contact_uri: CONTACT_URI,
+		register: true,
+		register_expires: REQUESTED_EXPIRES,
+	});
+
+	const events: Event[] = [];
+
+	const record =
+		(name: string) =>
+		({ expires, response }: RegisteredEvent): number =>
+			events.push({ name, expires, status: response.status_code });
+
+	ua.on('registered', record('registered'));
+	ua.on('registrationRefreshed', record('registrationRefreshed'));
+
+	await startUA(ua);
+
+	// The initial REGISTER is answered by then: refresh the binding.
+	await delay(50);
+
+	ua.register();
+
+	await delay(50);
+	await stopUA(ua);
+
+	return events;
+}
+
+describe('Registrator', () => {
+	test('reports every successful REGISTER with the granted expiry', async () => {
+		const granted = 20;
+
+		await expect(runRegistration(granted)).resolves.toEqual([
+			{ name: 'registered', expires: granted, status: 200 },
+			{ name: 'registrationRefreshed', expires: granted, status: 200 },
+		]);
+	});
+
+	test('reports the granted expiry, not the refresh timer floor', async () => {
+		// Shorter than the floor JsSIP applies to its own refresh timer. The
+		// binding still dies when the registrar says it does, so reporting the
+		// floor would promise more lifetime than there is.
+		const granted = MIN_REGISTER_EXPIRES - 5;
+
+		await expect(runRegistration(granted)).resolves.toEqual([
+			{ name: 'registered', expires: granted, status: 200 },
+			{ name: 'registrationRefreshed', expires: granted, status: 200 },
+		]);
+	});
+});
diff --git a/src/test/test-SubscriberNotifier.ts b/src/test/test-SubscriberNotifier.ts
index ab61da0..2f54556 100644
--- a/src/test/test-SubscriberNotifier.ts
+++ b/src/test/test-SubscriberNotifier.ts
@@ -1,240 +1,278 @@
+import { setTimeout as delay } from 'timers/promises';
+
 import './include/common';
 import LoopSocket from './include/LoopSocket';
-import type { Socket } from '../Socket';
-
-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const JsSIP = require('../JsSIP.js');
-const { UA } = JsSIP;
-
-const enum STEP {
-	INIT = 0,
-	SOCKET_CONNECTED = 1,
-	SUBSCRIBE_SENT = 2,
-	UA_ON_NEWSUBSCRIBE = 3,
-	NOTIFIER_ON_SUBSCRIBE = 4,
-	SUBSCRIBER_ON_ACCEPTED = 5,
-	SUBSCRIBER_ON_ACTIVE = 6,
-	SUBSCRIBER_ON_NOTIFY_1 = 7,
-	NOTIFIER_ON_UNSUBSCRIBE = 8,
-	NOTIFIER_TERMINATED = 9,
-	SUBSCRIBER_ON_NOTIFY_2 = 10,
-	SUBSCRIBER_TERMINATED = 11,
+import TestSocket from './include/TestSocket';
+import {
+	buildRequest,
+	buildResponse,
+	cseq,
+	header,
+	method,
+	ruri,
+	startLine,
+	tag,
+} from './include/sipMessage';
+
+import { startUA, untilDisconnected } from './include/ua';
+
+import { UA } from '../JsSIP';
+import type { Subscriber } from '../Subscriber';
+import type { EventHeader, SubscriptionStateHeader } from '../Grammar';
+
+/**
+ * The values are strings so that a mismatch shows the names rather than the
+ * ordinals.
+ */
+enum EVENT {
+	UA_CONNECTED = 'ua connected',
+	SUBSCRIBE_SENT = 'subscriber sent the SUBSCRIBE',
+	UA_NEW_SUBSCRIBE = 'ua newSubscribe',
+	NOTIFIER_SUBSCRIBE = 'notifier subscribe',
+	NOTIFIER_UNSUBSCRIBE = 'notifier unsubscribe',
+	NOTIFIER_TERMINATED = 'notifier terminated',
+	SUBSCRIBER_ACCEPTED = 'subscriber accepted',
+	SUBSCRIBER_ACTIVE = 'subscriber active',
+	SUBSCRIBER_NOTIFY = 'subscriber notify',
+	SUBSCRIBER_TERMINATED = 'subscriber terminated',
 }

 // Expires header of every SUBSCRIBE sent through the socket.
-function sentSubscribeExpires(socket: LoopSocket): string[] {
-	return jest
-		.mocked(socket.send)
-		.mock.calls.map(([message]) => message)
-		.filter(message => message.startsWith('SUBSCRIBE '))
-		.map(message => /\r\nExpires: *(\d+)/i.exec(message)![1]);
+function sentSubscribeExpires(socket: TestSocket): string[] {
+	return socket
+		.requests('SUBSCRIBE')
+		.map(message => header(message, 'Expires'));
 }

 describe('subscriber/notifier communication', () => {
-	test('should handle subscriber/notifier communication', () =>
-		new Promise<void>(resolve => {
-			let step = STEP.INIT;
-
-			const TARGET = 'ikq';
-			const REQUEST_URI = 'sip:ikq@example.com';
-			const CONTACT_URI = 'sip:ikq@abcdefabcdef.invalid;transport=ws';
-			const SUBSCRIBE_ACCEPT = 'application/text, text/plain';
-			const EVENT_NAME = 'weather';
-			const CONTENT_TYPE = 'text/plain';
-			const WEATHER_REQUEST = 'Please report the weather condition';
-			const WEATHER_REPORT = '+20..+24°C, no precipitation, light wind';
-
-			// eslint-disable-next-line @typescript-eslint/no-explicit-any
-			function createSubscriber(ua: any): void {
-				const options = {
-					expires: 3600,
-					contentType: CONTENT_TYPE,
-				};
-
-				const subscriber = ua.subscribe(
-					TARGET,
-					EVENT_NAME,
-					SUBSCRIBE_ACCEPT,
-					options
-				);
-
-				subscriber.on('active', () => {
-					// 'receive notify with subscription-state: active'
-					expect(++step).toBe(STEP.SUBSCRIBER_ON_ACTIVE);
-				});
-
-				subscriber.on(
-					'notify',
-					(
-						isFinal: boolean,
-						notify: {
-							method: string;
-							getHeader: (name: string) => string;
-							parseHeader: (name: string) => { state: string };
-						},
-						body?: string,
-						contType?: string
-					) => {
-						step++;
-						// 'receive notify'
-						expect(
-							step === STEP.SUBSCRIBER_ON_NOTIFY_1 ||
-								step === STEP.SUBSCRIBER_ON_NOTIFY_2
-						).toBe(true);
-
-						expect(notify.method).toBe('NOTIFY');
-						expect(notify.getHeader('contact')).toBe(`<${CONTACT_URI}>`); // 'notify contact'
-						expect(body).toBe(WEATHER_REPORT); // 'notify body'
-						expect(contType).toBe(CONTENT_TYPE); // 'notify content-type'
-
-						const subsState = notify.parseHeader('subscription-state').state;
-
-						expect(
-							subsState === 'pending' ||
-								subsState === 'active' ||
-								subsState === 'terminated'
-						).toBe(true); // 'notify subscription-state'
-
-						// After receiving the first notify, send un-subscribe.
-						if (step === STEP.SUBSCRIBER_ON_NOTIFY_1) {
-							subscriber.terminate(WEATHER_REQUEST);
-						}
-					}
-				);
-
-				subscriber.on(
-					'terminated',
-					(
-						terminationCode: number,
-						reason: string | undefined,
-						retryAfter: number | undefined
-					) => {
-						expect(++step).toBe(STEP.SUBSCRIBER_TERMINATED);
-						expect(terminationCode).toBe(subscriber.C.FINAL_NOTIFY_RECEIVED);
-						expect(reason).toBeUndefined();
-						expect(retryAfter).toBeUndefined();
-
-						// The un-SUBSCRIBE, and no refresh after it.
-						expect(sentSubscribeExpires(socket)).toEqual(['3600', '0']);
-
-						ua.stop();
-					}
-				);
-
-				subscriber.on('accepted', () => {
-					expect(++step).toBe(STEP.SUBSCRIBER_ON_ACCEPTED);
-				});
+	const TARGET = 'ikq';
+	const REQUEST_URI = 'sip:ikq@example.com';
+	const CONTACT_URI = 'sip:ikq@abcdefabcdef.invalid;transport=ws';
+	const SUBSCRIBE_ACCEPT = 'application/text, text/plain';
+	const EVENT_NAME = 'weather';
+	const CONTENT_TYPE = 'text/plain';
+	const WEATHER_REQUEST = 'Please report the weather condition';
+	const WEATHER_REPORT = '+20..+24°C, no precipitation, light wind';
+	const EXPIRES = 3600;

-				subscriber.subscribe(WEATHER_REQUEST);
+	// What the notifier made of a SUBSCRIBE it received.
+	type SubscribeSeen = {
+		isUnsubscribe: boolean;
+		method: string;
+		contact: string | undefined;
+		accept: string | undefined;
+		body: string | undefined;
+		contentType: string | undefined;
+	};

-				expect(++step).toBe(STEP.SUBSCRIBE_SENT);
-			}
+	// What the subscriber made of a NOTIFY it received.
+	type NotifySeen = {
+		isFinal: boolean;
+		method: string;
+		contact: string | undefined;
+		state: string | undefined;
+		body: string | undefined;
+		contentType: string | undefined;
+	};

-			// eslint-disable-next-line @typescript-eslint/no-explicit-any
-			function createNotifier(ua: any, subscribe: any): void {
-				const notifier = ua.notify(subscribe, CONTENT_TYPE, { pending: false });
-
-				// Receive subscribe (includes initial)
-				notifier.on(
-					'subscribe',
-					(
-						isUnsubscribe: boolean,
-						subs: unknown,
-						body?: string,
-						contType?: string
-					) => {
-						expect(subscribe.method).toBe('SUBSCRIBE');
-						expect(subscribe.getHeader('contact')).toBe(`<${CONTACT_URI}>`); // 'subscribe contact'
-						expect(subscribe.getHeader('accept')).toBe(SUBSCRIBE_ACCEPT); // 'subscribe accept'
-						expect(body).toBe(WEATHER_REQUEST); // 'subscribe body'
-						expect(contType).toBe(CONTENT_TYPE); // 'subscribe content-type'
-
-						expect(++step).toBe(
-							isUnsubscribe
-								? STEP.NOTIFIER_ON_UNSUBSCRIBE
-								: STEP.NOTIFIER_ON_SUBSCRIBE
-						);
-						if (isUnsubscribe) {
-							// 'send final notify'
-							notifier.terminate(WEATHER_REPORT);
-						} else {
-							// 'send notify'
-							notifier.notify(WEATHER_REPORT);
-						}
-					}
-				);
+	type Result = {
+		/* The subscriber, which is where the termination codes live: they are
+		 * a plain object in the implementation, not reachable statically.
+		 */
+		subscriber: Subscriber;
+		// Everything that happened, in order.
+		events: EVENT[];
+		// The initial SUBSCRIBE, as the notifier side of the UA saw it.
+		initialSubscribe: { ruri: string; event: string | undefined };
+		subscribes: SubscribeSeen[];
+		notifies: NotifySeen[];
+		termination: {
+			code: number;
+			reason: string | undefined;
+			retryAfter: number | undefined;
+		};
+		// Expires of every SUBSCRIBE that left the UA.
+		sentExpires: string[];
+	};

-				// Example only. Never reached.
-				notifier.on('expired', () => {
-					notifier.terminate(WEATHER_REPORT, 'timeout');
-				});
+	/**
+	 * A UA subscribing to itself over a loop socket: it answers its own
+	 * SUBSCRIBE as a notifier, reports the weather once, and the subscriber
+	 * then unsubscribes.
+	 */
+	async function runSubscription(): Promise<Result> {
+		const socket = new LoopSocket();

-				notifier.on('terminated', () => {
-					expect(++step).toBe(STEP.NOTIFIER_TERMINATED);
-				});
+		const ua = new UA({
+			sockets: socket,
+			uri: REQUEST_URI,
+			contact_uri: CONTACT_URI,
+			register: false,
+		});

-				notifier.start();
-			}
+		const events: EVENT[] = [];
+		const subscribes: SubscribeSeen[] = [];
+		const notifies: NotifySeen[] = [];

-			// Start JsSIP UA with loop socket.
-			const socket = new LoopSocket(); // message sending itself, with modified Call-ID
+		let initialSubscribe!: Result['initialSubscribe'];
+		let termination!: Result['termination'];

-			jest.spyOn(socket, 'send');
+		// The notifier side.
+		ua.on('newSubscribe', ({ request }) => {
+			events.push(EVENT.UA_NEW_SUBSCRIBE);

-			const config = {
-				sockets: socket,
-				uri: REQUEST_URI,
-				contact_uri: CONTACT_URI,
-				register: false,
+			initialSubscribe = {
+				ruri: request.ruri.toString(),
+				event: request.parseHeader<EventHeader>('event')?.event,
 			};

-			const ua = new UA(config);
+			const notifier = ua.notify(request, CONTENT_TYPE, { pending: false });
+
+			notifier.on(
+				'subscribe',
+				(isUnsubscribe, subscribe, body, contentType) => {
+					events.push(
+						isUnsubscribe
+							? EVENT.NOTIFIER_UNSUBSCRIBE
+							: EVENT.NOTIFIER_SUBSCRIBE
+					);
+
+					subscribes.push({
+						isUnsubscribe,
+						method: subscribe.method,
+						contact: subscribe.getHeader('contact'),
+						accept: subscribe.getHeader('accept'),
+						body,
+						contentType,
+					});

-			// Uncomment to see SIP communication
-			// JsSIP.debug.enable('JsSIP:*');
+					if (isUnsubscribe) {
+						notifier.terminate(WEATHER_REPORT);
+					} else {
+						notifier.notify(WEATHER_REPORT);
+					}
+				}
+			);

-			// eslint-disable-next-line @typescript-eslint/no-explicit-any
-			ua.on('newSubscribe', (e: any) => {
-				expect(++step).toBe(STEP.UA_ON_NEWSUBSCRIBE);
+			notifier.on('terminated', () => events.push(EVENT.NOTIFIER_TERMINATED));

-				const subs = e.request;
-				const ev = subs.parseHeader('event');
+			notifier.start();
+		});

-				expect(subs.ruri.toString()).toBe(REQUEST_URI); // 'initial subscribe uri'
-				expect(ev.event).toBe(EVENT_NAME); // 'subscribe event'
+		await startUA(ua);
+		events.push(EVENT.UA_CONNECTED);

-				if (ev.event !== EVENT_NAME) {
-					subs.reply(489); // "Bad Event"
+		// The subscriber side.
+		const subscriber = ua.subscribe(TARGET, EVENT_NAME, SUBSCRIBE_ACCEPT, {
+			expires: EXPIRES,
+			contentType: CONTENT_TYPE,
+		});

-					return;
-				}
+		subscriber.on('accepted', () => events.push(EVENT.SUBSCRIBER_ACCEPTED));
+		subscriber.on('active', () => events.push(EVENT.SUBSCRIBER_ACTIVE));
+
+		subscriber.on('notify', (isFinal, notify, body, contentType) => {
+			events.push(EVENT.SUBSCRIBER_NOTIFY);
+
+			notifies.push({
+				isFinal,
+				method: notify.method,
+				contact: notify.getHeader('contact'),
+				state:
+					notify.parseHeader<SubscriptionStateHeader>('subscription-state')
+						?.state,
+				body,
+				contentType,
+			});

-				const accepts = subs.getHeaders('accept');
-				const canUse = accepts?.some((v: string) => v.includes(CONTENT_TYPE));
+			// The weather is in: unsubscribe.
+			if (!isFinal) {
+				subscriber.terminate(WEATHER_REQUEST);
+			}
+		});

-				expect(canUse).toBe(true); // 'notifier can use subscribe accept header'
+		subscriber.on('terminated', (code, reason, retryAfter) => {
+			events.push(EVENT.SUBSCRIBER_TERMINATED);

-				if (!canUse) {
-					subs.reply(406); // "Not Acceptable"
+			termination = { code, reason, retryAfter };

-					return;
-				}
+			ua.stop();
+		});

-				createNotifier(ua, subs);
-			});
+		subscriber.subscribe(WEATHER_REQUEST);
+		events.push(EVENT.SUBSCRIBE_SENT);

-			ua.on('connected', () => {
-				expect(++step).toBe(STEP.SOCKET_CONNECTED);
+		await untilDisconnected(ua);

-				createSubscriber(ua);
-			});
+		return {
+			subscriber,
+			events,
+			initialSubscribe,
+			subscribes,
+			notifies,
+			termination,
+			sentExpires: sentSubscribeExpires(socket),
+		};
+	}

-			ua.on('disconnected', () => {
-				resolve();
-			});
+	test('a subscription from the initial SUBSCRIBE to the final NOTIFY', async () => {
+		const result = await runSubscription();
+
+		expect(result.events).toEqual([
+			EVENT.UA_CONNECTED,
+			EVENT.SUBSCRIBE_SENT,
+			EVENT.UA_NEW_SUBSCRIBE,
+			EVENT.NOTIFIER_SUBSCRIBE,
+			EVENT.SUBSCRIBER_ACCEPTED,
+			EVENT.SUBSCRIBER_ACTIVE,
+			EVENT.SUBSCRIBER_NOTIFY,
+			EVENT.NOTIFIER_UNSUBSCRIBE,
+			EVENT.NOTIFIER_TERMINATED,
+			EVENT.SUBSCRIBER_NOTIFY,
+			EVENT.SUBSCRIBER_TERMINATED,
+		]);
+
+		expect(result.initialSubscribe).toEqual({
+			ruri: REQUEST_URI,
+			event: EVENT_NAME,
+		});
+
+		const subscribe = {
+			method: 'SUBSCRIBE',
+			contact: `<${CONTACT_URI}>`,
+			accept: SUBSCRIBE_ACCEPT,
+			body: WEATHER_REQUEST,
+			contentType: CONTENT_TYPE,
+		};
+
+		expect(result.subscribes).toEqual([
+			{ ...subscribe, isUnsubscribe: false },
+			// The un-SUBSCRIBE carries the same body as the initial one here,
+			// because that is what terminate() was given.
+			{ ...subscribe, isUnsubscribe: true },
+		]);
+
+		const notify = {
+			method: 'NOTIFY',
+			contact: `<${CONTACT_URI}>`,
+			body: WEATHER_REPORT,
+			contentType: CONTENT_TYPE,
+		};
+
+		expect(result.notifies).toEqual([
+			{ ...notify, isFinal: false, state: 'active' },
+			{ ...notify, isFinal: true, state: 'terminated' },
+		]);
+
+		expect(result.termination).toEqual({
+			code: result.subscriber.C.FINAL_NOTIFY_RECEIVED,
+			reason: undefined,
+			retryAfter: undefined,
+		});

-			ua.start();
-		}));
+		// The initial SUBSCRIBE and the un-SUBSCRIBE, with no refresh in between.
+		expect(result.sentExpires).toEqual([`${EXPIRES}`, '0']);
+	});

 	test('subscriber refuses a target that is not a SIP URI', () => {
 		const ua = new UA({
@@ -248,127 +286,117 @@ describe('subscriber/notifier communication', () => {
 		);
 	});

-	test('subscriber gets the final response with "terminated"', () =>
-		new Promise<void>(resolve => {
-			const ua = new UA({
-				sockets: new LoopSocket(),
-				uri: 'sip:ikq@example.com',
-				register: false,
-			});
+	test('subscriber gets the final response with "terminated"', async () => {
+		const ua = new UA({
+			sockets: new LoopSocket(),
+			uri: 'sip:ikq@example.com',
+			register: false,
+		});

-			// eslint-disable-next-line @typescript-eslint/no-explicit-any
-			ua.on('newSubscribe', (e: any) => {
-				e.request.reply(489); // "Bad Event"
-			});
+		ua.on('newSubscribe', e => {
+			e.request.reply(489); // "Bad Event"
+		});

-			ua.on('connected', () => {
-				const subscriber = ua.subscribe('ikq', 'weather', 'text/plain', {});
-
-				subscriber.on(
-					'terminated',
-					(
-						terminationCode: number,
-						reason: string | undefined,
-						retryAfter: number | undefined,
-						response: { status_code: number } | undefined
-					) => {
-						expect(terminationCode).toBe(
-							subscriber.C.SUBSCRIBE_NON_OK_RESPONSE
-						);
-						expect(reason).toBeUndefined();
-						expect(retryAfter).toBeUndefined();
-						expect(response?.status_code).toBe(489);
-
-						ua.stop();
-					}
-				);
+		await startUA(ua);

-				subscriber.subscribe();
-			});
+		const subscriber = ua.subscribe('ikq', 'weather', 'text/plain', {});

-			ua.on('disconnected', () => {
-				resolve();
-			});
+		let termination!: {
+			code: number;
+			reason: string | undefined;
+			retryAfter: number | undefined;
+			status: number | undefined;
+		};

-			ua.start();
-		}));
+		subscriber.on('terminated', (code, reason, retryAfter, response) => {
+			termination = { code, reason, retryAfter, status: response?.status_code };

-	test('UA.stop() unsubscribes', () =>
-		new Promise<void>(resolve => {
-			// A stopped UA drops incoming requests, so it cannot be its own
-			// notifier: the subscriber and the notifier are two UAs.
-			const [subscriberSocket, notifierSocket] = LoopSocket.pair();
+			ua.stop();
+		});

-			jest.spyOn(subscriberSocket, 'send');
+		subscriber.subscribe();

-			const subscriberUA = new UA({
-				sockets: subscriberSocket,
-				uri: 'sip:alice@example.com',
-				contact_uri: 'sip:alice@abcdefabcdef.invalid;transport=ws',
-				register: false,
-			});
+		await untilDisconnected(ua);

-			const notifierUA = new UA({
-				sockets: notifierSocket,
-				uri: 'sip:ikq@example.com',
-				contact_uri: 'sip:ikq@abcdefabcdef.invalid;transport=ws',
-				register: false,
-			});
+		expect(termination).toEqual({
+			code: subscriber.C.SUBSCRIBE_NON_OK_RESPONSE,
+			reason: undefined,
+			retryAfter: undefined,
+			status: 489,
+		});
+	});

-			let disconnected = 0;
+	test('UA.stop() unsubscribes', async () => {
+		// A stopped UA drops incoming requests, so it cannot be its own
+		// notifier: the subscriber and the notifier are two UAs.
+		const [subscriberSocket, notifierSocket] = LoopSocket.pair();

-			const onDisconnected = (): void => {
-				if (++disconnected === 2) {
-					resolve();
-				}
-			};
+		const subscriberUA = new UA({
+			sockets: subscriberSocket,
+			uri: 'sip:alice@example.com',
+			contact_uri: 'sip:alice@abcdefabcdef.invalid;transport=ws',
+			register: false,
+		});

-			// eslint-disable-next-line @typescript-eslint/no-explicit-any
-			notifierUA.on('newSubscribe', (e: any) => {
-				const notifier = notifierUA.notify(e.request, 'text/plain', {
-					pending: false,
-				});
+		const notifierUA = new UA({
+			sockets: notifierSocket,
+			uri: 'sip:ikq@example.com',
+			contact_uri: 'sip:ikq@abcdefabcdef.invalid;transport=ws',
+			register: false,
+		});

-				notifier.on('subscribe', (isUnsubscribe: boolean) => {
-					if (isUnsubscribe) {
-						notifier.terminate();
-					} else {
-						notifier.notify();
-					}
-				});
+		notifierUA.on('newSubscribe', e => {
+			const notifier = notifierUA.notify(e.request, 'text/plain', {
+				pending: false,
+			});

-				notifier.start();
+			notifier.on('subscribe', isUnsubscribe => {
+				if (isUnsubscribe) {
+					notifier.terminate();
+				} else {
+					notifier.notify();
+				}
 			});

-			subscriberUA.on('connected', () => {
-				const subscriber = subscriberUA.subscribe(
-					'sip:ikq@example.com',
-					'weather',
-					'text/plain',
-					{ expires: 3600 }
-				);
+			notifier.start();
+		});
+
+		await Promise.all([startUA(notifierUA), startUA(subscriberUA)]);

-				subscriber.on('active', () => {
-					subscriberUA.stop();
+		const subscriber = subscriberUA.subscribe(
+			'sip:ikq@example.com',
+			'weather',
+			'text/plain',
+			{ expires: EXPIRES }
+		);

-					expect(sentSubscribeExpires(subscriberSocket)).toEqual(['3600', '0']);
-				});
+		// What the subscriber had sent by the time its UA was stopped.
+		let sentOnStop: string[] = [];
+		let terminationCode: number | undefined;

-				subscriber.on('terminated', (terminationCode: number) => {
-					expect(terminationCode).toBe(subscriber.C.UA_STOPPED);
+		subscriber.on('active', () => {
+			subscriberUA.stop();

-					notifierUA.stop();
-				});
+			sentOnStop = sentSubscribeExpires(subscriberSocket);
+		});

-				subscriber.subscribe();
-			});
+		subscriber.on('terminated', code => {
+			terminationCode = code;

-			subscriberUA.on('disconnected', onDisconnected);
-			notifierUA.on('disconnected', onDisconnected);
+			notifierUA.stop();
+		});
+
+		subscriber.subscribe();

-			notifierUA.start();
-			subscriberUA.start();
-		}));
+		await Promise.all([
+			untilDisconnected(subscriberUA),
+			untilDisconnected(notifierUA),
+		]);
+
+		// The un-SUBSCRIBE left before the UA closed.
+		expect(sentOnStop).toEqual([`${EXPIRES}`, '0']);
+		expect(terminationCode).toBe(subscriber.C.UA_STOPPED);
+	});
 });

 // RFC 6665 4.1.2.4: the NOTIFY that creates the subscription dialog may reach
@@ -384,139 +412,62 @@ describe('subscriber receiving the initial NOTIFY', () => {
 	const NOTIFIER_TAG = 'notifiertag';
 	const EXPIRES = 3600;

-	function header(message: string, name: string): string {
-		return new RegExp(`^${name}: (.*)$`, 'mi').exec(message)![1];
-	}
-
-	function startLine(message: string): string {
-		return message.substring(0, message.indexOf('\r\n'));
-	}
-
 	/**
 	 * A socket that plays the notifier role by itself, so that the test decides
 	 * whether the initial NOTIFY travels before or after the 2xx response to the
 	 * initial SUBSCRIBE.
 	 */
-	class NotifierSocket implements Socket {
-		url = 'ws://localhost:12345';
-		via_transport = 'WS';
-		sip_uri = 'sip:localhost:12345;transport=ws';
-
-		// Every message written by the UA into the socket.
-		readonly sent: string[] = [];
-
+	class NotifierSocket extends TestSocket {
 		private notifyCount = 0;

-		constructor(private readonly notifyFirst: boolean) {}
-
-		connect(): void {
-			setTimeout(() => this.onconnect(), 0);
+		constructor(private readonly notifyFirst: boolean) {
+			super();
 		}

-		disconnect(): void {}
-
-		send(message: string): boolean {
-			this.sent.push(message);
-
-			if (message.startsWith('SUBSCRIBE ')) {
-				this.answerSubscribe(message);
+		protected override onRequest(request: string): void {
+			if (method(request) !== 'SUBSCRIBE') {
+				return;
 			}

-			return true;
-		}
-
-		isConnected(): boolean {
-			return true;
-		}
-
-		isConnecting(): boolean {
-			return false;
-		}
-
-		onconnect(): void {}
-
-		ondisconnect(): void {}
+			const expires = header(request, 'Expires');
+			const initial = !tag(header(request, 'To'));
+			const unsubscribe = expires === '0';

-		// eslint-disable-next-line @typescript-eslint/no-unused-vars
-		ondata(_data: string | ArrayBuffer): void {}
+			const ok = buildResponse(request, 200, {
+				toTag: NOTIFIER_TAG,
+				extraHeaders: [
+					`Contact: <${NOTIFIER_CONTACT_URI}>`,
+					`Expires: ${expires}`,
+				],
+			});

-		// The SUBSCRIBE requests sent by the UA.
-		get sentSubscribes(): string[] {
-			return this.sent.filter(message => message.startsWith('SUBSCRIBE '));
-		}
+			// The notifier only sends the initial and the final NOTIFY.
+			if (!initial && !unsubscribe) {
+				this.receive(ok);

-		// Status lines of the responses the UA gave to the NOTIFY requests.
-		get notifyResponses(): string[] {
-			return this.sent
-				.filter(
-					message =>
-						message.startsWith('SIP/2.0') &&
-						/\r\nCSeq: \d+ NOTIFY/.test(message)
-				)
-				.map(startLine);
-		}
+				return;
+			}

-		private answerSubscribe(subscribe: string): void {
-			const via = header(subscribe, 'Via');
-			const from = header(subscribe, 'From');
-			const callId = header(subscribe, 'Call-ID');
-			const cseq = header(subscribe, 'CSeq');
-			const expires = header(subscribe, 'Expires');
-			const initial = !/;tag=/i.test(header(subscribe, 'To'));
-			const to = initial
-				? `${header(subscribe, 'To')};tag=${NOTIFIER_TAG}`
-				: header(subscribe, 'To');
-
-			const ok = [
-				'SIP/2.0 200 OK',
-				`Via: ${via}`,
-				`From: ${from}`,
-				`To: ${to}`,
-				`Call-ID: ${callId}`,
-				`CSeq: ${cseq}`,
-				`Contact: <${NOTIFIER_CONTACT_URI}>`,
-				`Expires: ${expires}`,
-				'Content-Length: 0',
-				'',
-				'',
-			].join('\r\n');
+			const to = header(request, 'To');

-			// The notifier only sends the initial and the final NOTIFY.
-			const unsubscribe = expires === '0';
-			const messages = [ok];
-
-			if (initial || unsubscribe) {
-				const notifyCseq = ++this.notifyCount;
-				const body = unsubscribe ? '' : WEATHER_REPORT;
-
-				const notify = [
-					`NOTIFY ${SUBSCRIBER_CONTACT_URI} SIP/2.0`,
-					`Via: SIP/2.0/WS localhost:12345;branch=z9hG4bK.notify${notifyCseq}`,
-					'Max-Forwards: 69',
-					`From: ${to}`,
-					`To: ${from}`,
-					`Call-ID: ${callId}`,
-					`CSeq: ${notifyCseq} NOTIFY`,
+			const notify = buildRequest('NOTIFY', SUBSCRIBER_CONTACT_URI, {
+				from: initial ? `${to};tag=${NOTIFIER_TAG}` : to,
+				to: header(request, 'From'),
+				callId: header(request, 'Call-ID'),
+				cseq: ++this.notifyCount,
+				extraHeaders: [
 					`Event: ${EVENT_NAME}`,
 					unsubscribe
 						? 'Subscription-State: terminated;reason=timeout'
 						: `Subscription-State: active;expires=${EXPIRES}`,
 					`Contact: <${NOTIFIER_CONTACT_URI}>`,
-					`Content-Type: ${CONTENT_TYPE}`,
-					`Content-Length: ${body.length}`,
-					'',
-					body,
-				].join('\r\n');
-
-				if (initial && this.notifyFirst) {
-					messages.unshift(notify);
-				} else {
-					messages.push(notify);
-				}
-			}
+				],
+				contentType: CONTENT_TYPE,
+				body: unsubscribe ? '' : WEATHER_REPORT,
+			});

-			messages.forEach((message, index) =>
-				setTimeout(() => this.ondata(message), index + 1)
+			this.receive(
+				...(initial && this.notifyFirst ? [notify, ok] : [ok, notify])
 			);
 		}
 	}
@@ -547,74 +498,66 @@ describe('subscriber receiving the initial NOTIFY', () => {
 		refreshCseqIncrement: 1,
 	};

-	function runSubscription(notifyFirst: boolean): Promise<Result> {
-		return new Promise<Result>(resolve => {
-			const socket = new NotifierSocket(notifyFirst);
+	async function runSubscription(notifyFirst: boolean): Promise<Result> {
+		const socket = new NotifierSocket(notifyFirst);

-			const ua = new UA({
-				sockets: socket,
-				uri: SUBSCRIBER_URI,
-				contact_uri: SUBSCRIBER_CONTACT_URI,
-				register: false,
-			});
+		const ua = new UA({
+			sockets: socket,
+			uri: SUBSCRIBER_URI,
+			contact_uri: SUBSCRIBER_CONTACT_URI,
+			register: false,
+		});

-			let accepted = 0;
-			let active = 0;
-			let terminatedByFinalNotify = false;
-			const notifies: (string | undefined)[] = [];
-
-			ua.on('connected', () => {
-				const subscriber = ua.subscribe(
-					NOTIFIER_URI,
-					EVENT_NAME,
-					CONTENT_TYPE,
-					{ expires: EXPIRES }
-				);
-
-				subscriber.on('accepted', () => accepted++);
-				subscriber.on('active', () => active++);
-				subscriber.on(
-					'notify',
-					(_isFinal: boolean, _request: unknown, body?: string) =>
-						notifies.push(body)
-				);
-				subscriber.on('terminated', (code: number) => {
-					terminatedByFinalNotify = code === subscriber.C.FINAL_NOTIFY_RECEIVED;
-
-					// Let the pending transactions die before closing the UA.
-					setTimeout(() => ua.stop(), 50);
-				});
-
-				subscriber.subscribe();
-
-				// Both the 2xx and the initial NOTIFY are delivered by then.
-				setTimeout(() => {
-					// Refresh. It must travel within the subscription dialog.
-					subscriber.subscribe();
-
-					setTimeout(() => subscriber.terminate(), 50);
-				}, 50);
-			});
+		let accepted = 0;
+		let active = 0;
+		let terminatedByFinalNotify = false;
+		const notifies: (string | undefined)[] = [];

-			ua.on('disconnected', () => {
-				const [initialSubscribe, refresh] = socket.sentSubscribes;
-				const cseq = (subscribe: string): number =>
-					Number(header(subscribe, 'CSeq').split(' ')[0]);
-
-				resolve({
-					accepted,
-					active,
-					notifies,
-					notifyResponses: socket.notifyResponses,
-					terminatedByFinalNotify,
-					refreshRequestUri: startLine(refresh).split(' ')[1],
-					refreshToTag: /;tag=([^;]+)/.exec(header(refresh, 'To'))?.[1],
-					refreshCseqIncrement: cseq(refresh) - cseq(initialSubscribe),
-				});
-			});
+		await startUA(ua);

-			ua.start();
+		const subscriber = ua.subscribe(NOTIFIER_URI, EVENT_NAME, CONTENT_TYPE, {
+			expires: EXPIRES,
 		});
+
+		subscriber.on('accepted', () => accepted++);
+		subscriber.on('active', () => active++);
+		subscriber.on('notify', (_isFinal, _request, body) => notifies.push(body));
+		subscriber.on('terminated', code => {
+			terminatedByFinalNotify = code === subscriber.C.FINAL_NOTIFY_RECEIVED;
+
+			// Let the pending transactions die before closing the UA.
+			setTimeout(() => ua.stop(), 50);
+		});
+
+		subscriber.subscribe();
+
+		// Both the 2xx and the initial NOTIFY are delivered by then.
+		await delay(50);
+
+		// Refresh. It must travel within the subscription dialog.
+		subscriber.subscribe();
+
+		await delay(50);
+
+		subscriber.terminate();
+
+		await untilDisconnected(ua);
+
+		const subscribes = socket.requests('SUBSCRIBE');
+		const initialSubscribe = subscribes[0]!;
+		const refresh = subscribes[1]!;
+
+		return {
+			accepted,
+			active,
+			notifies,
+			notifyResponses: socket.responses('NOTIFY').map(startLine),
+			terminatedByFinalNotify,
+			refreshRequestUri: ruri(refresh),
+			refreshToTag: tag(header(refresh, 'To')),
+			refreshCseqIncrement:
+				cseq(refresh).number - cseq(initialSubscribe).number,
+		};
 	}

 	test('after the 2xx response to the initial SUBSCRIBE', async () => {
diff --git a/src/test/test-UA.ts b/src/test/test-UA.ts
index 5e88b20..598a1f9 100644
--- a/src/test/test-UA.ts
+++ b/src/test/test-UA.ts
@@ -1,12 +1,14 @@
-/* eslint no-console: 0*/
+import { setTimeout as delay } from 'timers/promises';

 import './include/common';
 import * as consts from './include/consts';
-import type { Socket } from '../Socket';
+import RegistrarSocket from './include/RegistrarSocket';
+import { expectDefined } from './include/expect';
+import { startUA, stopUA, untilRegistered } from './include/ua';
+import { buildRequest } from './include/sipMessage';

-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const JsSIP = require('../JsSIP.js');
-const { UA, WebSocketInterface, Exceptions, C } = JsSIP;
+import { C, Exceptions, UA, WebSocketInterface } from '../JsSIP';
+import type { UAContactOptions } from '../UA';

 describe('UA', () => {
 	test('UA wrong configuration', () => {
@@ -16,28 +18,30 @@ describe('UA', () => {
 	});

 	test('UA no WS connection', () => {
-		const config = consts.UA_CONFIGURATION;
-		const wsSocket = new WebSocketInterface(consts.SOCKET_DESCRIPTION['url']);
-
-		config['sockets'] = wsSocket;
-
-		const ua = new UA(config);
+		const ua = new UA(
+			consts.uaConfiguration({
+				sockets: new WebSocketInterface(consts.SOCKET_DESCRIPTION.url),
+			})
+		);

 		expect(ua instanceof UA).toBeTruthy();

 		ua.start();

-		expect(ua.contact.toString()).toBe(
-			`<sip:${ua.contact.uri.user}@${ua.configuration.via_host};transport=ws>`
-		);
+		const { configuration, transport } = ua;
+
+		const contact = `sip:${ua.contact.uri.user}@${configuration.via_host};transport=ws`;
+
+		expect(ua.contact.toString()).toBe(`<${contact}>`);
 		expect(
-			ua.contact.toString({ outbound: false, anonymous: false, foo: true })
-		).toBe(
-			`<sip:${ua.contact.uri.user}@${ua.configuration.via_host};transport=ws>`
-		);
-		expect(ua.contact.toString({ outbound: true })).toBe(
-			`<sip:${ua.contact.uri.user}@${ua.configuration.via_host};transport=ws;ob>`
-		);
+			ua.contact.toString({
+				outbound: false,
+				anonymous: false,
+				// An option the library knows nothing about is ignored.
+				foo: true,
+			} as UAContactOptions)
+		).toBe(`<${contact}>`);
+		expect(ua.contact.toString({ outbound: true })).toBe(`<${contact};ob>`);
 		expect(ua.contact.toString({ anonymous: true })).toBe(
 			'<sip:anonymous@anonymous.invalid;transport=ws>'
 		);
@@ -45,54 +49,38 @@ describe('UA', () => {
 			'<sip:anonymous@anonymous.invalid;transport=ws;ob>'
 		);

-		for (const parameter in consts.UA_CONFIGURATION_AFTER_START) {
-			if (
-				Object.prototype.hasOwnProperty.call(
-					consts.UA_CONFIGURATION_AFTER_START,
-					parameter
-				)
-			) {
-				switch (parameter) {
-					case 'uri':
-					case 'registrar_server': {
-						// eslint-disable-next-line jest/no-conditional-expect
-						expect(ua.configuration[parameter].toString()).toBe(
-							consts.UA_CONFIGURATION_AFTER_START[parameter]
-						);
-						break;
-					}
-					case 'sockets': {
-						console.warn('IGNORE SOCKETS');
-						break;
-					}
-					default: {
-						// eslint-disable-next-line jest/no-conditional-expect
-						expect(ua.configuration[parameter]).toBe(
-							consts.UA_CONFIGURATION_AFTER_START[parameter]
-						);
-					}
-				}
-			}
-		}
-
-		const transport = consts.UA_TRANSPORT_AFTER_START;
-		const sockets = transport['sockets'];
-		const socket = sockets[0].socket;
-
-		expect(sockets.length).toEqual(ua.transport.sockets.length);
-		expect(sockets[0].weight).toEqual(ua.transport.sockets[0].weight);
-		expect(socket.via_transport).toEqual(ua.transport.via_transport);
-		expect(socket.sip_uri).toEqual(ua.transport.sip_uri);
-		expect(socket.url).toEqual(ua.transport.url);
-
-		expect(transport['recovery_options']).toEqual(
-			ua.transport.recovery_options
-		);
+		expectDefined(configuration.uri);
+		expectDefined(configuration.registrar_server);
+
+		expect({
+			uri: configuration.uri.toString(),
+			password: configuration.password,
+			display_name: configuration.display_name,
+			authorization_user: configuration.authorization_user,
+			instance_id: configuration.instance_id,
+			registrar_server: configuration.registrar_server.toString(),
+			register_expires: configuration.register_expires,
+			register: configuration.register,
+			use_preloaded_route: configuration.use_preloaded_route,
+			no_answer_timeout: configuration.no_answer_timeout,
+			session_timers: configuration.session_timers,
+		}).toEqual(consts.UA_CONFIGURATION_AFTER_START);
+
+		expect({
+			sockets: transport.sockets.map(({ socket, weight }) => ({
+				socket: {
+					via_transport: socket.via_transport,
+					sip_uri: socket.sip_uri,
+					url: socket.url,
+				},
+				weight,
+			})),
+			recovery_options: transport.recovery_options,
+		}).toEqual(consts.UA_TRANSPORT_AFTER_START);

 		ua.sendMessage('test', 'FAIL WITH CONNECTION_ERROR PLEASE', {
 			eventHandlers: {
-				// eslint-disable-next-line @typescript-eslint/no-explicit-any
-				failed: function (e: any) {
+				failed: e => {
 					expect(e.cause).toEqual(C.causes.CONNECTION_ERROR);
 				},
 			},
@@ -114,135 +102,50 @@ const PUB_GRUU =
 	'sip:alice@example.com;gr=urn:uuid:3d1b40b8-07e4-4f5e-9d5b-1c2d3e4f5a6b';
 const TEMP_GRUU = 'sip:uloc-65a69615-354ff-915-b804a376@example.com;gr';

-function header(message: string, name: string): string {
-	return new RegExp(`^${name}: (.*)$`, 'mi').exec(message)![1];
-}
-
-/**
- * A socket that plays a registrar granting both a public and a temporary GRUU.
- */
-class GruuRegistrarSocket implements Socket {
-	url = 'ws://localhost:12345';
-	via_transport = 'WS';
-	sip_uri = 'sip:localhost:12345;transport=ws';
-
-	private readonly sent: string[] = [];
-
-	connect(): void {
-		setTimeout(() => this.onconnect(), 0);
-	}
-
-	disconnect(): void {}
-
-	send(message: string): boolean {
-		this.sent.push(message);
-
-		if (message.startsWith('REGISTER ')) {
-			setTimeout(() => this.ondata(this.answerRegister(message)), 1);
-		}
-
-		return true;
-	}
-
-	isConnected(): boolean {
-		return true;
-	}
-
-	isConnecting(): boolean {
-		return false;
-	}
-
-	onconnect(): void {}
-
-	ondisconnect(): void {}
-
-	// eslint-disable-next-line @typescript-eslint/no-unused-vars
-	ondata(_data: string | ArrayBuffer): void {}
-
-	receive(message: string): void {
-		this.ondata(message);
-	}
-
-	/**
-	 * Status code of the response sent for the given Call-ID.
-	 */
-	statusFor(call_id: string): number | undefined {
-		const response = this.sent.find(
-			message =>
-				message.startsWith('SIP/2.0 ') && header(message, 'Call-ID') === call_id
-		);
-
-		return response ? Number(response.slice(8, 11)) : undefined;
-	}
-
-	private answerRegister(register: string): string {
-		// Echo the Contact back (RFC 3261 10.3), with the granted GRUUs.
-		const contact =
-			`${header(register, 'Contact')}` +
-			`;pub-gruu="${PUB_GRUU}";temp-gruu="${TEMP_GRUU}"`;
-
-		return [
-			'SIP/2.0 200 OK',
-			`Via: ${header(register, 'Via')}`,
-			`From: ${header(register, 'From')}`,
-			`To: ${header(register, 'To')};tag=registrartag`,
-			`Call-ID: ${header(register, 'Call-ID')}`,
-			`CSeq: ${header(register, 'CSeq')}`,
-			`Contact: ${contact}`,
-			'Content-Length: 0',
-			'',
-			'',
-		].join('\r\n');
-	}
-}
-
-function bye(ruri: string, call_id: string): string {
-	return [
-		`BYE ${ruri} SIP/2.0`,
-		`Via: SIP/2.0/WS proxy.example.com;branch=z9hG4bK${call_id}`,
-		'Max-Forwards: 69',
-		'From: <sip:bob@example.com>;tag=remotetag',
-		`To: <${AOR}>;tag=localtag`,
-		`Call-ID: ${call_id}`,
-		'CSeq: 102 BYE',
-		'Content-Length: 0',
-		'',
-		'',
-	].join('\r\n');
+// An in-dialog BYE for a dialog the UA knows nothing about.
+function bye(requestUri: string, callId: string): string {
+	return buildRequest('BYE', requestUri, {
+		from: '<sip:bob@example.com>;tag=remotetag',
+		to: `<${AOR}>;tag=localtag`,
+		callId,
+		cseq: 102,
+	});
 }

 /**
  * Registers, then feeds the UA an in-dialog BYE per given Request-URI and
  * returns the status code each one is answered with.
  */
-function runByes(
+async function runByes(
 	ruris: Record<string, string>
 ): Promise<Record<string, number | undefined>> {
-	return new Promise(resolve => {
-		const socket = new GruuRegistrarSocket();
+	const socket = new RegistrarSocket({
+		pubGruu: PUB_GRUU,
+		tempGruu: TEMP_GRUU,
+	});

-		const ua = new UA({ sockets: socket, uri: AOR, register: true });
+	const ua = new UA({ sockets: socket, uri: AOR, register: true });

-		ua.on('registered', () => {
-			for (const name of Object.keys(ruris)) {
-				socket.receive(bye(ruris[name], name));
-			}
+	const registered = untilRegistered(ua);

-			setTimeout(() => ua.stop(), 50);
-		});
+	await startUA(ua);
+	await registered;

-		ua.on('disconnected', () => {
-			const statuses: Record<string, number | undefined> = {};
+	// The GRUUs are known only once the registrar has granted them.
+	for (const [name, requestUri] of Object.entries(ruris)) {
+		socket.receive(bye(requestUri, name));
+	}

-			for (const name of Object.keys(ruris)) {
-				statuses[name] = socket.statusFor(name);
-			}
+	await delay(50);
+	await stopUA(ua);

-			resolve(statuses);
-		});
+	const statuses: Record<string, number | undefined> = {};

-		ua.start();
-	});
+	for (const name of Object.keys(ruris)) {
+		statuses[name] = socket.statusFor(name);
+	}
+
+	return statuses;
 }

 describe('UA Request-URI check', () => {
@@ -275,3 +178,39 @@ describe('UA Request-URI check', () => {
 		).resolves.toEqual({ stranger: 404, 'foreign-gruu': 404 });
 	});
 });
+
+describe('UA.stop()', () => {
+	// CLOSE_TIMEOUT in src/UA.js.
+	const CLOSE_TIMEOUT = 2000;
+
+	// How long a registered UA takes to close once stopped.
+	async function timeStop(answerUnregister: boolean): Promise<number> {
+		const socket = new RegistrarSocket();
+		const ua = new UA({ sockets: socket, uri: AOR, register: true });
+
+		const registered = untilRegistered(ua);
+
+		await startUA(ua);
+		await registered;
+
+		socket.answering = answerUnregister;
+
+		const started = Date.now();
+
+		await stopUA(ua);
+
+		return Date.now() - started;
+	}
+
+	test('closes as soon as the pending transactions are done', async () => {
+		// The un-REGISTER is answered, so there is nothing left to wait for.
+		expect(await timeStop(true)).toBeLessThan(CLOSE_TIMEOUT / 4);
+	});
+
+	test('closes anyway when they never finish', async () => {
+		const elapsed = await timeStop(false);
+
+		expect(elapsed).toBeGreaterThanOrEqual(CLOSE_TIMEOUT);
+		expect(elapsed).toBeLessThan(CLOSE_TIMEOUT * 2);
+	});
+});
diff --git a/src/test/test-URI.ts b/src/test/test-URI.ts
index 11a514d..d274514 100644
--- a/src/test/test-URI.ts
+++ b/src/test/test-URI.ts
@@ -1,12 +1,10 @@
 import './include/common';

-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const JsSIP = require('../JsSIP.js');
-const { URI } = JsSIP;
+import { URI } from '../JsSIP';

 describe('URI', () => {
 	test('new URI', () => {
-		const uri = new URI(null, 'alice', 'jssip.net', 6060);
+		const uri = new URI(undefined, 'alice', 'jssip.net', 6060);

 		expect(uri.scheme).toBe('sip');
 		expect(uri.user).toBe('alice');
@@ -30,17 +28,18 @@ describe('URI', () => {
 		uri.user = '%61lice';
 		expect(uri.toAor()).toBe('sip:alice@jssip.net');

-		uri.user = null;
-		expect(uri.user).toBeNull();
+		uri.user = undefined;
+		expect(uri.user).toBeUndefined();
 		expect(uri.toAor()).toBe('sip:jssip.net');
 		uri.user = 'alice';

+		// What an untyped JavaScript caller can still pass.
 		expect(() => {
-			uri.host = null;
+			uri.host = null as unknown as string;
 		}).toThrow(TypeError);

 		expect(() => {
-			uri.host = { bar: 'foo' };
+			uri.host = { bar: 'foo' } as unknown as string;
 		}).toThrow(TypeError);

 		expect(uri.host).toBe('jssip.net');
diff --git a/src/test/test-Utils.ts b/src/test/test-Utils.ts
index cd65c3c..5319239 100644
--- a/src/test/test-Utils.ts
+++ b/src/test/test-Utils.ts
@@ -1,8 +1,6 @@
 import './include/common';

-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const JsSIP = require('../JsSIP.js');
-const { URI, Utils } = JsSIP;
+import { URI, Utils } from '../JsSIP';

 describe('Utils', () => {
 	test('normalizeTarget() valid targets', () => {
diff --git a/src/test/test-parser.ts b/src/test/test-parser.ts
index d199744..dcd7fe3 100644
--- a/src/test/test-parser.ts
+++ b/src/test/test-parser.ts
@@ -1,11 +1,10 @@
 import './include/common';
 import * as consts from './include/consts';

-// eslint-disable-next-line @typescript-eslint/no-require-imports
-const JsSIP = require('../JsSIP.js');
-const { URI, NameAddrHeader, Grammar, WebSocketInterface, UA } = JsSIP;
-
+import { Grammar, NameAddrHeader, UA, URI, WebSocketInterface } from '../JsSIP';
 import * as Parser from '../Parser';
+import { expectDefined } from './include/expect';
+import type { UALike } from '../SIPMessage';

 describe('parser', () => {
 	test('parse URI', () => {
@@ -14,6 +13,7 @@ describe('parser', () => {
 		const uri = URI.parse(data);

 		// Parsed data.
+		expectDefined(uri);
 		expect(uri instanceof URI).toBeTruthy();
 		expect(uri.scheme).toBe('sip');
 		expect(uri.user).toBe('aliCE');
@@ -56,6 +56,7 @@ describe('parser', () => {
 		const name = NameAddrHeader.parse(data);

 		// Parsed data.
+		expectDefined(name);
 		expect(name instanceof NameAddrHeader).toBeTruthy();
 		expect(name.display_name).toBe(
 			'Iñaki ðđøþ foo "bar" \\\\ \\ \\d \\\\d \\\' \\"sdf\\"'
@@ -68,6 +69,7 @@ describe('parser', () => {

 		const uri = name.uri;

+		expectDefined(uri);
 		expect(uri instanceof URI).toBeTruthy();
 		expect(uri.scheme).toBe('sip');
 		expect(uri.user).toBe('aliCE');
@@ -86,8 +88,8 @@ describe('parser', () => {
 		// Alter data.
 		name.display_name = 'Foo Bar';
 		expect(name.display_name).toBe('Foo Bar');
-		name.display_name = null;
-		expect(name.display_name).toBe(null);
+		name.display_name = undefined;
+		expect(name.display_name).toBeUndefined();
 		expect(name.toString()).toBe(
 			'<sip:aliCE@versatica.com:6060;transport=tcp;foo=ABc;baz?X-Header-1=AaA1&X-Header-1=AAA2&X-Header-2=BbB>;qwe=QWE;asd'
 		);
@@ -101,11 +103,13 @@ describe('parser', () => {
 		const name = NameAddrHeader.parse(data);

 		// Parsed data.
+		expectDefined(name);
 		expect(name instanceof NameAddrHeader).toBeTruthy();
 		expect(name.display_name).toBe(buffer.toString());

 		const uri = name.uri;

+		expectDefined(uri);
 		expect(uri instanceof URI).toBeTruthy();
 		expect(uri.scheme).toBe('sip');
 		expect(uri.user).toBe('foo');
@@ -119,6 +123,7 @@ describe('parser', () => {
 		const name = NameAddrHeader.parse(data);

 		// Parsed data.
+		expectDefined(name);
 		expect(name instanceof NameAddrHeader).toBeTruthy();
 		expect(name.display_name).toBe('Foo Foo Bar Baz');
 	});
@@ -129,6 +134,7 @@ describe('parser', () => {
 		const name = NameAddrHeader.parse(data);

 		// Parsed data.
+		expectDefined(name);
 		expect(name instanceof NameAddrHeader).toBeTruthy();
 		expect(name.display_name).toBe('Foo');
 	});
@@ -139,6 +145,7 @@ describe('parser', () => {
 		const name = NameAddrHeader.parse(data);

 		// Parsed data.
+		expectDefined(name);
 		expect(name instanceof NameAddrHeader).toBeTruthy();
 		expect(name.display_name).toBe(undefined);
 	});
@@ -205,7 +212,7 @@ describe('parser', () => {

 		// Parsed data.
 		expect(c3 instanceof NameAddrHeader).toBeTruthy();
-		expect(c3.displayName).toBe(undefined);
+		expect(c3.display_name).toBe(undefined);
 		expect(c3.uri instanceof URI).toBeTruthy();
 		expect(c3.uri.scheme).toBe('sip');
 		expect(c3.uri.user).toBe(undefined);
@@ -421,13 +428,16 @@ Max-Forwards: 70\r\n\
 Privacy: id\r\n\
 P-Preferred-Identity: "Cullen Jennings" <sip:fluffy@cisco.com>\r\n\r\n';

-		const config = consts.UA_CONFIGURATION;
-		const wsSocket = new WebSocketInterface(consts.SOCKET_DESCRIPTION['url']);
-
-		config['sockets'] = wsSocket;
+		const ua = new UA(
+			consts.uaConfiguration({
+				sockets: new WebSocketInterface(consts.SOCKET_DESCRIPTION.url),
+			})
+		);

-		const ua = new UA(config as ConstructorParameters<typeof UA>[0]);
-		const message = Parser.parseMessage(data, ua);
+		/* A started UA does satisfy UALike, but no exported type says so: see the
+		 * TODO on 'Configuration', which UA mutates after loading it.
+		 */
+		const message = Parser.parseMessage(data, ua as unknown as UALike);

 		if (!message) {
 			throw new Error('parseMessage() did not return a message');
@@ -436,8 +446,13 @@ P-Preferred-Identity: "Cullen Jennings" <sip:fluffy@cisco.com>\r\n\r\n';
 		expect(message.hasHeader('P-Preferred-Identity')).toBe(true);

 		const pai = message.getHeader('P-Preferred-Identity');
+
+		expectDefined(pai);
+
 		const nameAddress = NameAddrHeader.parse(pai);

+		expectDefined(nameAddress);
+
 		expect(nameAddress instanceof NameAddrHeader).toBeTruthy();
 		expect(nameAddress.uri.user).toBe('fluffy');
 		expect(nameAddress.uri.host).toBe('cisco.com');
diff --git a/tsconfig.build.json b/tsconfig.build.json
new file mode 100644
index 0000000..45b2398
--- /dev/null
+++ b/tsconfig.build.json
@@ -0,0 +1,4 @@
+{
+	"extends": "./tsconfig.json",
+	"exclude": ["src/test"]
+}
diff --git a/tsconfig.json b/tsconfig.json
index cc59ba4..fb73494 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -2,6 +2,7 @@
 	"compileOnSave": true,
 	"compilerOptions": {
 		"lib": ["es2024", "dom"],
+		"types": ["node", "jest"],
 		"module": "NodeNext",
 		"moduleResolution": "NodeNext",
 		"outDir": "lib",
@@ -39,6 +40,7 @@
 		"useUnknownInCatchVariables": true,
 		"noUncheckedSideEffectImports": true,
 	},
+	// NOTE: The tests are included so that `tsc --noEmit` type checks them too.
+	// `tsconfig.build.json` excludes them, so that they don't end in lib/.
 	"include": ["src"],
-	"exclude": ["src/test"],
 }