Quick answer: Test a Node.js worker message at both ends. Verify the receiver's value and byte range, then check whether the sender still owns readable storage. JSON text, a structured clone, and a transferred buffer can all deliver useful data, but each makes a different promise about what remains available after sending.
A worker can return the right checksum while the caller loses the bytes it needs for a retry. A test that checks only the checksum misses that failure. These five local fixtures use Node.js v24.22.1 and MessageChannel to isolate message semantics. They do not measure worker startup, scheduling, throughput, or memory use.
1. How can a test distinguish JSON text from a cloned message object?
Send an explicit JSON string if the recipient expects a text protocol, and assert that it arrives as a string before parsing. Send a plain object directly if both ends agree to structured cloning. Test the decoded field values in either case, because matching values alone cannot tell you which transport representation arrived.
Save the JavaScript blocks in order as one file named worker-messages.mjs, then run node worker-messages.mjs. Each fixture opens a fresh pair of ports and closes them afterward. The synchronous receive call is convenient because the sender and receiver live in the same process and the messages in these examples are queued before the receive call. In production, a worker typically consumes messages through an event handler. The Node.js v24 worker threads reference documents both APIs. For background on the related browser model, see Wikipedia's Web Worker overview.
import assert from 'node:assert/strict';
import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
function throughPort(run) {
const { port1, port2 } = new MessageChannel();
try {
const read = () => receiveMessageOnPort(port2).message;
run(port1, read);
} finally {
port1.close();
port2.close();
}
}
throughPort((port, read) => {
const job = { id: 'scan-28', byteCount: 3 };
port.postMessage(JSON.stringify(job));
const text = read();
assert.equal(typeof text, 'string');
assert.deepEqual(JSON.parse(text), job);
port.postMessage(job);
assert.deepEqual(read(), job);
});
Use a text contract when a downstream boundary really needs one, such as a persisted record that a different language reads. If the text message has a version field, assert it alongside the representation: a worker that reads the old contract may parse the new message without understanding it. The JavaScript JSON guide explains the parse and stringify boundary in more depth.
To review changes in two synthetic job envelopes, paste the JSON text from each version into JSON Compare. Inspect the field differences there and keep the type assertion in code. The tool sees the submitted documents; it cannot observe the worker channel or prove that any buffer was transferred.
A fixture with both sends also guards against an accidental second encoding. Imagine a wrapper serializes every job while its caller already provides serialized text. Parsing once then returns a string, and a consumer looking for a job ID sees no field. A strict comparison to the expected object catches that case. Keep the representative fixture small enough to read at a glance, and make any coercion the receiver is supposed to accept a separate test.
2. How can a test prove the sender kept its own copy of the bytes?
Post a typed array without a transfer list, mutate the sender's bytes after posting, and check that the receiver still gets the original values. Verify that the sender's view is still readable. Together those checks show that the receiver got a snapshot and that the sender can keep using its storage.
throughPort((port, read) => {
const bytes = Uint8Array.of(12, 24, 36);
port.postMessage({ bytes });
bytes[0] = 99;
const message = read();
assert.ok(message.bytes instanceof Uint8Array);
assert.deepEqual([...message.bytes], [12, 24, 36]);
assert.deepEqual([...bytes], [99, 24, 36]);
});
The mutation makes this a useful regression test. If all you check is that the arrays have the same elements immediately after sending, a shared view can appear to work. This fixture uses ordinary ArrayBuffer storage. Node also supports messages containing SharedArrayBuffer; its shared memory has different semantics and needs tests designed for concurrent access. See the postMessage documentation for the distinction.
A copy is a reasonable baseline when the sender keeps a retry queue or reads the same data to update a preview. Keep that choice explicit in the test name so a future optimization cannot remove it unnoticed. This example confirms isolation after one send. It says nothing about the cost of copying large payloads repeatedly. If volume matters, measure the payload sizes, queue behavior, and workload that your service actually sees. For a comparison with cloning through a text representation, see the JSON deep clone guide.
If you use these checks in a real worker integration test, arrange a reply that reports what the worker received. A reply containing just a length does not tell you if the bytes were correct, and it does not tell you whether the sender can reuse them. A useful fixture asserts the reply and then reads a known sender byte. Keep the same mutation in the local test so you can diagnose a change in message behavior without starting a worker.
3. How can a test catch sender views that become detached after transfer?
Create two views over the same ordinary ArrayBuffer, then send one view with the buffer in the transfer list. Verify that the receiver can read the expected bytes and that both sender views lose access to their storage. An unsent sibling view can be affected even though it never appears in the message.
throughPort((port, read) => {
const bytes = Uint8Array.of(10, 20, 30, 40);
const tail = bytes.subarray(2);
const storage = bytes.buffer;
port.postMessage({ bytes }, [storage]);
assert.equal(storage.byteLength, 0);
assert.equal(bytes.byteLength, 0);
assert.equal(tail.byteLength, 0);
assert.deepEqual([...read().bytes], [10, 20, 30, 40]);
});
The sibling view represents a common source of surprises: the caller may pass a small slice to another function and forget that both parts refer to the same allocation. Node's typed array transfer notes explain that transferring the backing buffer affects every view over it. The receiver's successful read is only half of the contract.
Trace ownership back to the allocation when reviewing a transfer. If the buffer came from an upstream component, that component might still have a view even if your function holds only one reference. Put the transfer near the point where the owner agrees to give up the bytes. Also decide how to recover if the worker rejects a job after delivery. The original sender cannot reconstruct detached contents from the detached view. It needs another source, a separately retained copy, or an application protocol that returns the bytes. Test that recovery separately from successful message delivery.
The detachment check uses a buffer that was nonempty before sending. A zero length by itself is ambiguous if your original allocation held no bytes. Keep a nonempty test case even if the production protocol also accepts empty chunks. For an integration test, record the state immediately after posting and check the reply separately. This distinguishes a successful handoff followed by a worker failure from an error raised during the send itself.
4. How can a test detect a backing buffer that Node will refuse to transfer?
Check whether Node has marked the backing ArrayBuffer as untransferable, and test the failure with a known marked allocation. On the Node.js v24 runtime used here, listing that buffer for transfer throws a DataCloneError. Copy the visible bytes into a new owned buffer when the source allocation cannot be moved safely.
import {
isMarkedAsUntransferable, markAsUntransferable,
} from 'node:worker_threads';
throughPort((port, read) => {
const bytes = Uint8Array.of(7, 8, 9);
markAsUntransferable(bytes.buffer);
assert.ok(isMarkedAsUntransferable(bytes.buffer));
assert.throws(() => port.postMessage(bytes, [bytes.buffer]), {
name: 'DataCloneError',
});
assert.deepEqual([...bytes], [7, 8, 9]);
assert.ok(isMarkedAsUntransferable(Buffer.allocUnsafe(8).buffer));
const copy = Uint8Array.from(bytes);
port.postMessage(copy, [copy.buffer]);
assert.deepEqual([...read()], [7, 8, 9]);
});
The explicit mark keeps the error case independent of how your app allocated its input. The tiny Buffer.allocUnsafe assertion separately checks the default pool on the tested runtime; the fixture never reads those uninitialized bytes. Node's untransferable buffer documentation describes the mark and explains why Node applies it to backing storage used by its buffer pool. Your app should not assume every Buffer comes from that pool. Construction method matters, and buffers returned from dependencies may have an allocation history you cannot see.
Treat the mark as a useful rejection signal. Its absence alone does not establish that you have exclusive access or permission to detach the allocation. When a helper accepts arbitrary byte views, an owned copy makes the ownership rule explicit and predictable. It also gives you somewhere to put a test for the exact number of bytes you mean to send.
Avoid silently switching to a copy on every exception from the send. That can hide an invalid message or a programming error in the transfer list. For example, if an envelope also contains an unsupported value, copying the byte view cannot fix the envelope. Decide up front when your adapter is allowed to copy and when it should fail. The marked fixture gives you one known failure case without needing to infer the cause from a runtime error message.
5. How can a test ensure only the intended byte slice reaches the receiver?
Copy the view into a fresh Uint8Array and transfer the fresh array's backing buffer. At the receiver, check both the visible bytes and the backing buffer length. A subarray on its own only limits the view; it can still expose a buffer that contains bytes outside the intended message range.
throughPort((port, read) => {
const whole = Uint8Array.of(200, 12, 24, 201);
const visible = whole.subarray(1, 3);
const outbound = Uint8Array.from(visible);
port.postMessage({ bytes: outbound }, [outbound.buffer]);
const { bytes } = read();
assert.deepEqual([...bytes], [12, 24]);
assert.deepEqual([...new Uint8Array(bytes.buffer)], [12, 24]);
assert.equal(bytes.buffer.byteLength, 2);
assert.equal(bytes.byteOffset, 0);
assert.deepEqual([...whole], [200, 12, 24, 201]);
});
The two outside values act as sentinels. Checking the visible elements alone would still pass if a larger allocation arrived and the received view hid the extra bytes. Reading the full received backing buffer makes the test sensitive to that mistake. This matters when one allocation holds several records, and a function has permission to send only the one represented by its slice. For production code, also enforce the expected maximum message size before allocating a copy if the input can be large.
Copying a slice and then transferring it does include a copy at the source. The benefit here is a precise ownership and byte boundary; any performance comparison needs its own benchmark. If the bytes must leave Node.js inside a JSON document, decide on a text representation separately and verify it with binary data encoding tests for JSON. That is a different boundary from the local worker channel. Keeping the tests separate lets a failure tell you whether the envelope changed, the wrong bytes crossed, or the sender lost data it still needed.
A useful follow-up is to test two slices from one backing allocation as separate jobs. Each result should carry only its own bytes, and sending the first job should leave the source usable for the second. That fixture mirrors a batch splitter more closely than five unrelated allocations would. If you already own an allocation whose entire contents are intended for one recipient and nobody needs it afterward, the earlier direct transfer fixture is the better model. Choose the test according to what the caller owns and what the recipient may read.