示例工程 13-esm

13-esm/03-dynamic-import/main.test.mjs

javascript · 0.9 KB

运行:13 · 动态 import()

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

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { load, run } from './main.js';
 
test('import() 返回 Promise', () => {
  const p = load('./lazy.js');
  assert.equal(p instanceof Promise, true);
  return p;
});
 
test('动态导入拿到命名导出与默认导出', async () => {
  const mod = await load('./lazy.js');
  assert.equal(mod.value, 42);
  assert.equal(mod.default('Ada'), 'hi Ada');
});
 
test('同一 URL 的动态导入返回同一模块对象', async () => {
  const first = await load('./lazy.js');
  const second = await load('./lazy.js');
  assert.equal(first, second);
});
 
test('缺失模块以 rejection 形式失败', async () => {
  await assert.rejects(() => load('./missing.js'));
});
 
test('run 汇总结果', async () => {
  const out = [];
  const result = await run((s) => out.push(s));
  assert.deepEqual(result, { value: 42, same: true });
  assert.match(out.at(-1), /只求值一次/);
});