Node.js 18 更新一览: 内置 fetch、Test Runner 模块等

1,631

Node.js 18 近期发布了 18.0.0 版本,我们来看一下该版本的更新内容有哪些;

  • 支持 Fetch 功能
  • 支持 Test Runner 单元测试
  • 改进对 ECMAScript 的模块
  • 改进了对 AbortControllerAbortSignal 的支持

fetch 功能

Node.js 18 内置了 fetch 模块,fetch API 可全局调用,无需引入 node-fetch

const res = await fetch('https://api.belo.app/public/price');
if (res.ok) {
  const data = await res.json();
  console.log(data);
}

Test Runner 功能

Test Runner 单元测试功能是非常重要的,在 Node.js 18 以前,我们需要借助第三方模块库来实现该功能,例如 Mocha、Jest 等。

下面我们来看一下 Node.js 18 中如何使用该模块。

import test from 'node:test';
import assert from 'node:assert';

test('synchronous passing test', (t) => {
  // This test passes because it does not throw an exception.
  assert.strictEqual(1, 1);
});

测试字符串

test("Testing a string", () => {
   assert.match("Welcome Node 18", /Node 18/);
});

上面测试会输出:

  ok 1 - Testing a string
  ---
  duration_ms: 0.000385918
  ...

上面我们使用的 test 方法,第一个参数使当前测试的描述,回调函数作为第二个参数,函数中我们定义测试逻辑。

如果我们要断言一个字符串,那么我们需要将字符串作为第一个参数,回调函数中来发送正则表达式。例如下面代码:

test("Testing a string fails", () => {
   assert.match("Hello", /world/, 'This string does not contain "world"');
});

我们得到结果如下:

image.png

测试两数相等与否

我们来使用 assert 上的 equalnotEqual 来测试两个值是否相等。

test("Testing that a number is equal", () => {
   let current = 99;
   let expected = 99;
   assert.equal(actual, expected);
});

test("Testing that a number is not equal", () => {
   let current = 22;
   let expected = 393;
   assert.notEqual(actual, expected, `${actual} is not equal to ${expected}`);
});

测试异步功能

如果你想测试异步函数,可以借助 await 来实现 Promise

test("Testing asynchronous functionality", async() => {
   const number = await Promise.resolve(90);
   assert.equal(number, 90, "The number is not equal to 90");
});

子测试

我们还可以在父测试中对子测试进行分组

test('top level test', async (t) => {
  await t.test('subtest 1', (t) => {
    assert.strictEqual(1, 1);
  });

  await t.test('subtest 2', (t) => {
    assert.strictEqual(2, 2);
  });
});

如果你想了解更多关于此次更新的讯息,请参考: dev.to/jordandev/n…