0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-24 20:29:23 +01:00
nodejs/test/parallel/test-worker-message-port-transfer-self.js
Anna Henningsen 5adda2c447
worker: use fake MessageEvent for port.onmessage
Instead of passing the payload for Workers directly to `.onmessage`,
perform something more similar to what the browser API provides,
namely create an event object with a `.data` property.

This does not make `MessagePort` implement the `EventTarget` API, nor
does it implement the full `MessageEvent` API, but it would make
such extensions non-breaking changes if we desire them at
some point in the future.

(This would be a breaking change if Workers were not experimental.
Currently, this method is also undocumented and only exists with
the idea of enabling some degree of Web compatibility.)

PR-URL: https://github.com/nodejs/node/pull/26082
Reviewed-By: Gus Caplan <me@gus.host>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Denys Otrishko <shishugi@gmail.com>
2019-02-15 23:16:16 +01:00

45 lines
1.4 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const util = require('util');
const { MessageChannel } = require('worker_threads');
const tick = require('../common/tick');
const { port1, port2 } = new MessageChannel();
assert.throws(common.mustCall(() => {
port1.postMessage(null, [port1]);
}), common.mustCall((err) => {
assert.strictEqual(err.name, 'DataCloneError');
assert.strictEqual(err.message, 'Transfer list contains source port');
assert.strictEqual(err.code, 25);
assert.ok(err instanceof Error);
const DOMException = err.constructor;
assert.ok(err instanceof DOMException);
assert.strictEqual(DOMException.name, 'DOMException');
return true;
}));
// The failed transfer should not affect the ports in anyway.
port2.onmessage = common.mustCall((message) => {
assert.strictEqual(message.data, 2);
const inspectedPort1 = util.inspect(port1);
const inspectedPort2 = util.inspect(port2);
assert(inspectedPort1.includes('active: true'), inspectedPort1);
assert(inspectedPort2.includes('active: true'), inspectedPort2);
port1.close();
tick(10, () => {
const inspectedPort1 = util.inspect(port1);
const inspectedPort2 = util.inspect(port2);
assert(inspectedPort1.includes('active: false'), inspectedPort1);
assert(inspectedPort2.includes('active: false'), inspectedPort2);
});
});
port1.postMessage(2);