2 /* eslint-disable capitalized-comments */
3 /* eslint-disable security/detect-object-injection */
6 const assert
= require('assert');
7 const { lazy
} = require('../index');
9 describe('lazy', function () {
10 let o
, initializer
, called
;
12 beforeEach(function () {
21 it('does not initialize if not accessed', function () {
22 lazy(o
, 'p', initializer
);
23 assert
.strictEqual(called
, 0);
24 assert(Object
.keys(o
).includes('p'));
27 it('requires a callable initializer', function () {
29 lazy(o
, 'p', undefined);
30 assert
.fail('should reject un-callable initializer');
32 assert(e
instanceof TypeError
, `expected 'TypeError', got '${e.name}'`);
36 it('initializes once when accessed', function () {
37 lazy(o
, 'p', initializer
);
40 assert
.strictEqual(called
, 1);
41 assert
.strictEqual(v
, 'value');
42 assert
.strictEqual(v2
, 'value');
45 it('handles symbolic properties', function () {
46 const s
= Symbol('s');
47 lazy(o
, s
, initializer
);
49 assert
.strictEqual(called
, 1);
50 assert
.strictEqual(v
, 'value');
53 it('can be overwritten before being read', function () {
54 const expected
= 'foobar';
55 lazy(o
, 'p', initializer
);
58 assert
.strictEqual(v
, expected
);
59 assert
.strictEqual(called
, 0);
62 it('cannot be overwritten before being read if eventually not writable', function () {
63 lazy(o
, 'p', initializer
, {
68 assert
.fail('should disallow setting non-writable property');
70 assert(e
instanceof TypeError
, `expected 'TypeError', got ${e.name}`);
74 it('async initializer awkwardly needs await on all gets but technically works', async
function () {
75 lazy(o
, 'p', async () => {
80 assert
.strictEqual(called
, 1);
81 assert
.strictEqual(v
, 'value');
84 it('prototypical lazy sets value on prototype by default', function () {
85 lazy(o
, 'p', initializer
);
87 const o1
= Object
.create(o
);
89 const o2
= Object
.create(o
);
94 assert
.strictEqual(v1
, 'value');
95 assert
.strictEqual(v2
, 'value');
96 assert
.strictEqual(called
, 1);
97 assert(!Object
.hasOwnProperty
.call(o1
, 'p'));
98 assert(!Object
.hasOwnProperty
.call(o2
, 'p'));
101 it('prototypical lazy sets value on inherited objects when requested', function () {
102 lazy(o
, 'p', initializer
, undefined, false);
104 const o1
= Object
.create(o
);
106 const o2
= Object
.create(o
);
111 assert
.strictEqual(v1
, 'value');
112 assert
.strictEqual(v2
, 'value');
113 assert
.strictEqual(called
, 2);
114 assert(Object
.hasOwnProperty
.call(o1
, 'p'));
115 assert(Object
.hasOwnProperty
.call(o2
, 'p'));