| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import lazyInit from '../lazyInit'; |
| 9 | |
| 10 | describe('lazyInit', () => { |
| 11 | test('async operation never called', () => { |
| 12 | let numCalls = 0; |
| 13 | let theObject; |
| 14 | function expensiveObjCreation() { |
| 15 | ++numCalls; |
| 16 | theObject = {}; |
| 17 | return Promise.resolve(theObject); |
| 18 | } |
| 19 | |
| 20 | const getObj = lazyInit(expensiveObjCreation); |
| 21 | expect(typeof getObj).toBe('function'); |
| 22 | expect(theObject).toBe(undefined); |
| 23 | expect(numCalls).toBe(0); |
| 24 | }); |
| 25 | |
| 26 | test('async operation called when value requested', async () => { |
| 27 | let numCalls = 0; |
| 28 | let theObject; |
| 29 | function expensiveObjCreation() { |
| 30 | ++numCalls; |
| 31 | theObject = {}; |
| 32 | return Promise.resolve(theObject); |
| 33 | } |
| 34 | |
| 35 | const getObj = lazyInit(expensiveObjCreation); |
| 36 | expect(numCalls).toBe(0); |
| 37 | const obj = await getObj(); |
| 38 | expect(numCalls).toBe(1); |
| 39 | expect(obj).toBe(theObject); |
| 40 | }); |
| 41 | |
| 42 | test('async operation called only once when value requested many times', async () => { |
| 43 | let numCalls = 0; |
| 44 | let theObject; |
| 45 | function expensiveObjCreation() { |
| 46 | ++numCalls; |
| 47 | theObject = {}; |
| 48 | return Promise.resolve(theObject); |
| 49 | } |
| 50 | |
| 51 | const getObj = lazyInit(expensiveObjCreation); |
| 52 | expect(numCalls).toBe(0); |
| 53 | |
| 54 | const obj1 = await getObj(); |
| 55 | const obj2 = await getObj(); |
| 56 | const obj3 = await getObj(); |
| 57 | expect(numCalls).toBe(1); |
| 58 | expect(obj1).toBe(theObject); |
| 59 | expect(obj2).toBe(theObject); |
| 60 | expect(obj3).toBe(theObject); |
| 61 | }); |
| 62 | }); |
| 63 | |