单元测试很重要,很多新兴的编程语言都是会内置对应的能力,但 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生成。
真诚赞赏,手留余香
赞赏