summaryrefslogtreecommitdiffstats
path: root/devtools/shared/tests/xpcshell/test_eventemitter_basic.js
blob: caf2186bffa0386f81a0712d23f9075d858fe77e (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const {
  ConsoleAPIListener,
} = require("resource://devtools/server/actors/webconsole/listeners/console-api.js");
const EventEmitter = require("resource://devtools/shared/event-emitter.js");
const hasMethod = (target, method) =>
  method in target && typeof target[method] === "function";

/**
 * Each method of this object is a test; tests can be synchronous or asynchronous:
 *
 * 1. Plain functions are synchronous tests.
 * 2. methods with `async` keyword are asynchronous tests.
 * 3. methods with `done` as argument are asynchronous tests (`done` needs to be called to
 *    finish the test).
 */
const TESTS = {
  testEventEmitterCreation() {
    const emitter = getEventEmitter();
    const isAnEmitter = emitter instanceof EventEmitter;

    ok(emitter, "We have an event emitter");
    ok(
      hasMethod(emitter, "on") &&
        hasMethod(emitter, "off") &&
        hasMethod(emitter, "once") &&
        hasMethod(emitter, "count") &&
        !hasMethod(emitter, "decorate"),
      `Event Emitter ${
        isAnEmitter ? "instance" : "mixin"
      } has the expected methods.`
    );
  },

  testEmittingEvents(done) {
    const emitter = getEventEmitter();

    let beenHere1 = false;
    let beenHere2 = false;

    function next(str1, str2) {
      equal(str1, "abc", "Argument 1 is correct");
      equal(str2, "def", "Argument 2 is correct");

      ok(!beenHere1, "first time in next callback");
      beenHere1 = true;

      emitter.off("next", next);

      emitter.emit("next");

      emitter.once("onlyonce", onlyOnce);

      emitter.emit("onlyonce");
      emitter.emit("onlyonce");
    }

    function onlyOnce() {
      ok(!beenHere2, '"once" listener has been called once');
      beenHere2 = true;
      emitter.emit("onlyonce");

      done();
    }

    emitter.on("next", next);
    emitter.emit("next", "abc", "def");
  },

  testThrowingExceptionInListener(done) {
    const emitter = getEventEmitter();
    const listener = new ConsoleAPIListener(null, message => {
      equal(message.level, "error");
      const [arg] = message.arguments;
      equal(arg.message, "foo");
      equal(arg.stack, "bar");
      listener.destroy();
      done();
    });

    listener.init();

    function throwListener() {
      emitter.off("throw-exception");
      const err = new Error("foo");
      err.stack = "bar";
      throw err;
    }

    emitter.on("throw-exception", throwListener);
    emitter.emit("throw-exception");
  },

  testKillItWhileEmitting(done) {
    const emitter = getEventEmitter();

    const c1 = () => ok(true, "c1 called");
    const c2 = () => {
      ok(true, "c2 called");
      emitter.off("tick", c3);
    };
    const c3 = () => ok(false, "c3 should not be called");
    const c4 = () => {
      ok(true, "c4 called");
      done();
    };

    emitter.on("tick", c1);
    emitter.on("tick", c2);
    emitter.on("tick", c3);
    emitter.on("tick", c4);

    emitter.emit("tick");
  },

  testOffAfterOnce() {
    const emitter = getEventEmitter();

    let enteredC1 = false;
    const c1 = () => (enteredC1 = true);

    emitter.once("oao", c1);
    emitter.off("oao", c1);

    emitter.emit("oao");

    ok(!enteredC1, "c1 should not be called");
  },

  testPromise() {
    const emitter = getEventEmitter();
    const p = emitter.once("thing");

    // Check that the promise is only resolved once event though we
    // emit("thing") more than once
    let firstCallbackCalled = false;
    const check1 = p.then(arg => {
      equal(firstCallbackCalled, false, "first callback called only once");
      firstCallbackCalled = true;
      equal(arg, "happened", "correct arg in promise");
      return "rval from c1";
    });

    emitter.emit("thing", "happened", "ignored");

    // Check that the promise is resolved asynchronously
    let secondCallbackCalled = false;
    const check2 = p.then(arg => {
      ok(true, "second callback called");
      equal(arg, "happened", "correct arg in promise");
      secondCallbackCalled = true;
      equal(arg, "happened", "correct arg in promise (a second time)");
      return "rval from c2";
    });

    // Shouldn't call any of the above listeners
    emitter.emit("thing", "trashinate");

    // Check that we can still separate events with different names
    // and that it works with no parameters
    const pfoo = emitter.once("foo");
    const pbar = emitter.once("bar");

    const check3 = pfoo.then(arg => {
      Assert.strictEqual(arg, undefined, "no arg for foo event");
      return "rval from c3";
    });

    pbar.then(() => {
      ok(false, "pbar should not be called");
    });

    emitter.emit("foo");

    equal(secondCallbackCalled, false, "second callback not called yet");

    return Promise.all([check1, check2, check3]).then(args => {
      equal(args[0], "rval from c1", "callback 1 done good");
      equal(args[1], "rval from c2", "callback 2 done good");
      equal(args[2], "rval from c3", "callback 3 done good");
    });
  },

  testClearEvents() {
    const emitter = getEventEmitter();

    const received = [];
    const listener = (...args) => received.push(args);

    emitter.on("a", listener);
    emitter.on("b", listener);
    emitter.on("c", listener);

    emitter.emit("a", 1);
    emitter.emit("b", 1);
    emitter.emit("c", 1);

    equal(received.length, 3, "the listener was triggered three times");

    emitter.clearEvents();
    emitter.emit("a", 1);
    emitter.emit("b", 1);
    emitter.emit("c", 1);
    equal(received.length, 3, "the listener was not called after clearEvents");
  },

  testOnReturn() {
    const emitter = getEventEmitter();

    let called = false;
    const removeOnTest = emitter.on("test", () => {
      called = true;
    });

    equal(typeof removeOnTest, "function", "`on` returns a function");
    removeOnTest();

    emitter.emit("test");
    equal(called, false, "event listener wasn't called");
  },

  async testEmitAsync() {
    const emitter = getEventEmitter();

    let resolve1, resolve2;
    emitter.once("test", async () => {
      return new Promise(r => {
        resolve1 = r;
      });
    });

    // Adding a listener which doesn't return a promise should trigger a console warning.
    emitter.once("test", () => {});

    emitter.once("test", async () => {
      return new Promise(r => {
        resolve2 = r;
      });
    });

    info("Emit an event and wait for all listener resolutions");
    const onConsoleWarning = onConsoleWarningLogged(
      "Listener for event 'test' did not return a promise."
    );
    const onEmitted = emitter.emitAsync("test");
    let resolved = false;
    onEmitted.then(() => {
      info("emitAsync just resolved");
      resolved = true;
    });

    info("Waiting for warning message about the second listener");
    await onConsoleWarning;

    // Spin the event loop, to ensure that emitAsync did not resolved too early
    await new Promise(r => Services.tm.dispatchToMainThread(r));

    ok(resolve1, "event listener has been called");
    ok(!resolved, "but emitAsync hasn't resolved yet");

    info("Resolve the first listener function");
    resolve1();
    ok(!resolved, "emitAsync isn't resolved until all listener resolve");

    info("Resolve the second listener function");
    resolve2();

    // emitAsync is only resolved in the next event loop
    await new Promise(r => Services.tm.dispatchToMainThread(r));
    ok(resolved, "once we resolve all the listeners, emitAsync is resolved");
  },

  testCount() {
    const emitter = getEventEmitter();

    equal(emitter.count("foo"), 0, "no listeners for 'foo' events");
    emitter.on("foo", () => {});
    equal(emitter.count("foo"), 1, "listener registered");
    emitter.on("foo", () => {});
    equal(emitter.count("foo"), 2, "another listener registered");
    emitter.off("foo");
    equal(emitter.count("foo"), 0, "listeners unregistered");
  },
};

// Wait for the next call to console.warn which includes
// the text passed as argument
function onConsoleWarningLogged(warningMessage) {
  return new Promise(resolve => {
    const ConsoleAPIStorage = Cc[
      "@mozilla.org/consoleAPI-storage;1"
    ].getService(Ci.nsIConsoleAPIStorage);

    const observer = subject => {
      // This is the first argument passed to console.warn()
      const message = subject.wrappedJSObject.arguments[0];
      if (message.includes(warningMessage)) {
        ConsoleAPIStorage.removeLogEventListener(observer);
        resolve();
      }
    };

    ConsoleAPIStorage.addLogEventListener(
      observer,
      Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal)
    );
  });
}

/**
 * Create a runnable tests based on the tests descriptor given.
 *
 * @param {Object} tests
 *  The tests descriptor object, contains the tests to run.
 */
const runnable = tests =>
  async function () {
    for (const name of Object.keys(tests)) {
      info(name);
      if (tests[name].length === 1) {
        await new Promise(resolve => tests[name](resolve));
      } else {
        await tests[name]();
      }
    }
  };

// We want to run the same tests for both an instance of `EventEmitter` and an object
// decorate with EventEmitter; therefore we create two strategies (`createNewEmitter` and
// `decorateObject`) and a factory (`getEventEmitter`), where the factory is the actual
// function used in the tests.

const createNewEmitter = () => new EventEmitter();
const decorateObject = () => EventEmitter.decorate({});

// First iteration of the tests with a new instance of `EventEmitter`.
let getEventEmitter = createNewEmitter;
add_task(runnable(TESTS));
// Second iteration of the tests with an object decorate using `EventEmitter`
add_task(() => (getEventEmitter = decorateObject));
add_task(runnable(TESTS));