summaryrefslogtreecommitdiffstats
path: root/devtools/shared/tests/xpcshell/test_defineLazyPrototypeGetter.js
blob: 2f53b377de58bd79a3a3471d37681f26bf098b82 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

// Test DevToolsUtils.defineLazyPrototypeGetter

function Class() {}
DevToolsUtils.defineLazyPrototypeGetter(Class.prototype, "foo", () => []);

function run_test() {
  test_prototype_attributes();
  test_instance_attributes();
  test_multiple_instances();
  test_callback_receiver();
}

function test_prototype_attributes() {
  // Check that the prototype has a getter property with expected attributes.
  const descriptor = Object.getOwnPropertyDescriptor(Class.prototype, "foo");
  Assert.equal(typeof descriptor.get, "function");
  Assert.equal(descriptor.set, undefined);
  Assert.equal(descriptor.enumerable, false);
  Assert.equal(descriptor.configurable, true);
}

function test_instance_attributes() {
  // Instances should not have an own property until the lazy getter has been
  // activated.
  const instance = new Class();
  Assert.ok(!instance.hasOwnProperty("foo"));
  instance.foo;
  Assert.ok(instance.hasOwnProperty("foo"));

  // Check that the instance has an own property with the expecred value and
  // attributes after the lazy getter is activated.
  const descriptor = Object.getOwnPropertyDescriptor(instance, "foo");
  Assert.ok(descriptor.value instanceof Array);
  Assert.equal(descriptor.writable, true);
  Assert.equal(descriptor.enumerable, false);
  Assert.equal(descriptor.configurable, true);
}

function test_multiple_instances() {
  const instance1 = new Class();
  const instance2 = new Class();
  const foo1 = instance1.foo;
  const foo2 = instance2.foo;
  // Check that the lazy getter returns the expected type of value.
  Assert.ok(foo1 instanceof Array);
  Assert.ok(foo2 instanceof Array);
  // Make sure the lazy getter runs once and only once per instance.
  Assert.equal(instance1.foo, foo1);
  Assert.equal(instance2.foo, foo2);
  // Make sure each instance gets its own unique value.
  Assert.notEqual(foo1, foo2);
}

function test_callback_receiver() {
  function Foo() {}
  DevToolsUtils.defineLazyPrototypeGetter(Foo.prototype, "foo", function () {
    return this;
  });

  // Check that the |this| value in the callback is the instance itself.
  const instance = new Foo();
  Assert.equal(instance.foo, instance);
}