Node.js 18.x 开始支持内置单元测试

单元测试很重要,很多新兴的编程语言都是会内置对应的能力,但 Node.js 这块一直都是由社区来实现,前端同学耳熟能详的 Test Runner 有 Mocha、Jest。

2022年04月19日正式发布的 Node.js 18.x ,终于,官方支持了 Test 能力。Fetch API 也被集成到这个版本中了。测试 API 接口在一定程度上代替 SuperTest 了。

代码:

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

// 等价于 describe()
test('asynchronous passing test', async () => {
  const res = await fetch('https://nodejs.org/api/documentation.json');
  assert(res.ok);
});

test('multi level test', async (t) => {
  // 等价于 it()
  await t.test('subtest 1', (t) => {
    assert.strictEqual(1, 1);
  });

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

// 等价于 describe.skip() / it.skip()
test('skip option', { skip: true }, () => {});

// 等价于 describe.only() / it.only()
test('only option', { only: true }, () => {});


之前单元测试的方法:

https://javascript.net.cn/articles/865

https://javascript.net.cn/articles/864

https://javascript.net.cn/articles/770

https://javascript.net.cn/articles/581


提示:

此模块稳定性还处于实验阶段,在任何未来的版本中都可能发生非向后兼容的更改或删除。 不建议在生产环境中使用该特性。


声明:本站所有文章,如无特殊说明或,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。本站所有图片如无特殊说明均为AI生成。
真诚赞赏,手留余香
赞赏
MySQL
如何使用命令修改 MySQL 数据库名称
2022-03-27
前端
FFmpeg 修改默认音轨
2022-05-01
Jone
在什么样的花园里面,挖呀挖呀挖
种什么样的种子,开什么样的花
随机推荐
Node.js MySQL 连接池和事务
Git 放弃本地修改,强制和之前的某次提交同步
MySQL 字符串截取函数 SUBSTRING_INDEX
MySQL 的 sql_mode 模式介绍:为什么 MySQL 中 int,float,double 类型字段插入空字符时自动转为0
FFmpeg 修改默认音轨
macOS 生成 icns 图标
数据库中间表应该如何命名
如何使用命令修改 MySQL 数据库名称
JavaScript 原生拖放
Node.js 使用 Jest 和 supertest 做接口测试

微信联系我

夜间模式切换
回到顶部