summaryrefslogtreecommitdiff
path: root/test/parallel/test-worker-message-port-move.js
blob: 44efd2e6a6b94f7710d5ed7d503ca9cc999de8c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* global port */
'use strict';
const common = require('../common');
const assert = require('assert');
const vm = require('vm');
const {
  MessagePort, MessageChannel, moveMessagePortToContext
} = require('worker_threads');

const context = vm.createContext();
const { port1, port2 } = new MessageChannel();
context.port = moveMessagePortToContext(port1, context);
context.global = context;
Object.assign(context, {
  global: context,
  assert,
  MessagePort,
  MessageChannel
});

vm.runInContext('(' + function() {
  {
    assert(port.postMessage instanceof Function);
    assert(port.constructor instanceof Function);
    for (let obj = port; obj !== null; obj = Object.getPrototypeOf(obj)) {
      for (const key of Object.getOwnPropertyNames(obj)) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
          assert(obj[key] instanceof Object);
        } else if (typeof obj[key] === 'function') {
          assert(obj[key] instanceof Function);
        }
      }
    }

    assert(!(port instanceof MessagePort));
    assert.strictEqual(port.onmessage, undefined);
    port.onmessage = function({ data, ports }) {
      assert(data instanceof Object);
      assert(ports instanceof Array);
      assert.strictEqual(ports.length, 1);
      assert.strictEqual(ports[0], data.p);
      assert(!(data.p instanceof MessagePort));
      port.postMessage({});
    };
    port.start();
  }

  {
    let threw = false;
    try {
      port.postMessage(global);
    } catch (e) {
      assert.strictEqual(e.constructor.name, 'DOMException');
      assert(e instanceof Object);
      assert(e instanceof Error);
      threw = true;
    }
    assert(threw);
  }
} + ')()', context);

const otherChannel = new MessageChannel();
port2.on('message', common.mustCall((msg) => {
  assert(msg instanceof Object);
  port2.close();
  otherChannel.port2.close();
}));
port2.postMessage({ p: otherChannel.port1 }, [ otherChannel.port1 ]);