summaryrefslogtreecommitdiffstats
path: root/services/common/tests/unit/test_observers.js
blob: b0fce95e0b51282a8b65ea487186d4aced369783 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

const { Observers } = ChromeUtils.importESModule(
  "resource://services-common/observers.sys.mjs"
);

var gSubject = {};

add_test(function test_function_observer() {
  let foo = false;

  let onFoo = function (subject, data) {
    foo = !foo;
    Assert.equal(subject, gSubject);
    Assert.equal(data, "some data");
  };

  Observers.add("foo", onFoo);
  Observers.notify("foo", gSubject, "some data");

  // The observer was notified after being added.
  Assert.ok(foo);

  Observers.remove("foo", onFoo);
  Observers.notify("foo");

  // The observer was not notified after being removed.
  Assert.ok(foo);

  run_next_test();
});

add_test(function test_method_observer() {
  let obj = {
    foo: false,
    onFoo(subject, data) {
      this.foo = !this.foo;
      Assert.equal(subject, gSubject);
      Assert.equal(data, "some data");
    },
  };

  // The observer is notified after being added.
  Observers.add("foo", obj.onFoo, obj);
  Observers.notify("foo", gSubject, "some data");
  Assert.ok(obj.foo);

  // The observer is not notified after being removed.
  Observers.remove("foo", obj.onFoo, obj);
  Observers.notify("foo");
  Assert.ok(obj.foo);

  run_next_test();
});

add_test(function test_object_observer() {
  let obj = {
    foo: false,
    observe(subject, topic, data) {
      this.foo = !this.foo;

      Assert.equal(subject, gSubject);
      Assert.equal(topic, "foo");
      Assert.equal(data, "some data");
    },
  };

  Observers.add("foo", obj);
  Observers.notify("foo", gSubject, "some data");

  // The observer is notified after being added.
  Assert.ok(obj.foo);

  Observers.remove("foo", obj);
  Observers.notify("foo");

  // The observer is not notified after being removed.
  Assert.ok(obj.foo);

  run_next_test();
});