示例工程 13-esm

13-esm/02-top-level-this/main.test.mjs

javascript · 0.7 KB

运行:13 · 模块顶层 this

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { globalObject, run, topLevelThis } from './main.js';
 
test('ESM 顶层 this 是 undefined', () => {
  assert.equal(topLevelThis, undefined);
});
 
test('globalThis 仍然指向全局对象', () => {
  assert.equal(typeof globalObject(), 'object');
  assert.equal(globalObject(), globalThis);
});
 
test('顶层不是 globalThis 的别名', () => {
  assert.notEqual(topLevelThis, globalThis);
});
 
test('run 输出环境结论', () => {
  const out = [];
  const result = run((s) => out.push(s));
  assert.equal(result.topLevelThis, undefined);
  assert.equal(result.hasGlobalThis, true);
  assert.match(out[0], /undefined/);
});