Node.js 单元测试

本文被收录到:

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 }, () => {});

 

接口单元测试:

const assert = require('node:assert/strict');
const test = require('node:test');

const host = 'http://127.0.0.1:3000';
const headers = new Headers();
headers.append('Content-Type', 'application/json');

test('auth', async function (t) {
  await t.test('required account work fine with undefined', async () => {
    let url = host + '/v1/auth/login';
    let payload = { password:'123456'};

    let response = await fetch(url,{ method:'POST', headers, body: JSON.stringify(payload)});
    let json = await response.json();
    assert.deepEqual(json, { error: 'account is required' });
  });
  
  await t.test('incorrect username or password', async () => {
    let url = host + '/v1/auth/login';
    let payload = { account:'test@qq.com', password:'123456' };
  
    let response = await fetch(url,{ method:'POST', headers, body: JSON.stringify(payload)});
    let json = await response.json();
    assert.deepEqual(json, { error: 'incorrect username or password' });
  });


});

 

之前单元测试的方法:

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

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

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

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

修改时间 2024-05-28

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
搜神记
766 文章
4 教程
8 项目
随机推荐
JavaScript video 教程
WordPress 的用户角色和权限
Node.js test 模块
Node.js MySQL 连接池和事务
JavaScript 中的数据类型自动转换为 Boolean 状态
Nine 主题
Node.js 控制台进度条实现原理
Node.js net 模块