|
| 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 greet, {helper} from '../babel-style-default.cjs'; |
| 9 | +import plainDefault, {multiply, value} from '../plain-cjs.cjs'; |
| 10 | +import {getCount as countA, increment as incA} from '../importer-a.mjs'; |
| 11 | +import {getCount as countB, increment as incB} from '../importer-b.mjs'; |
| 12 | + |
| 13 | +// ── __esModule interop ──────────────────────────────────────────────────────── |
| 14 | + |
| 15 | +test('default import of __esModule CJS unwraps .default, not the whole exports', () => { |
| 16 | + // greet should be the function, not {__esModule: true, default: fn, helper: fn} |
| 17 | + expect(typeof greet).toBe('function'); |
| 18 | + expect(greet('World')).toBe('Hello, World!'); |
| 19 | +}); |
| 20 | + |
| 21 | +test('named imports of __esModule CJS work alongside default', () => { |
| 22 | + expect(helper(7)).toBe(14); |
| 23 | +}); |
| 24 | + |
| 25 | +test('__esModule key is not exposed as a named export', async () => { |
| 26 | + const ns = await import('../babel-style-default.cjs'); |
| 27 | + expect(Object.keys(ns)).not.toContain('__esModule'); |
| 28 | +}); |
| 29 | + |
| 30 | +// ── plain CJS (no __esModule flag) ─────────────────────────────────────────── |
| 31 | + |
| 32 | +test('default import of plain CJS is the whole module.exports object', () => { |
| 33 | + expect(plainDefault).toEqual({multiply: expect.any(Function), value: 99}); |
| 34 | +}); |
| 35 | + |
| 36 | +test('named imports from plain CJS work', () => { |
| 37 | + expect(value).toBe(99); |
| 38 | + expect(multiply(6, 7)).toBe(42); |
| 39 | +}); |
| 40 | + |
| 41 | +// ── CJS-as-ESM caching (singleton) ─────────────────────────────────────────── |
| 42 | + |
| 43 | +test('two ESM importers of the same CJS module share one singleton instance', () => { |
| 44 | + // importer-a and importer-b both re-export singleton-state.cjs. |
| 45 | + // If the CJS module is cached, mutations are visible across importers. |
| 46 | + incA(); |
| 47 | + incA(); |
| 48 | + incB(); // operates on the same underlying CJS export object |
| 49 | + expect(countA()).toBe(3); |
| 50 | + expect(countB()).toBe(3); |
| 51 | +}); |
0 commit comments