# node 的自动化测试

Node 有有一个内置的测试库 node:test
测试执行命令: npm script test
编写测试脚本让命令更简洁:

"scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "node --test" // 添加这个命令
  },

并创建一个 .test.js 文件,内容类似于:

const { test } = require('node:test')
const assert = require('node:assert') // 引入断言库
const reverse = require('../utils/for_testing').reverse
test('reverse of a', () => {
  const result = reverse('a')
  assert.strictEqual(result, 'a') // 断言是否全等
})
test('reverse of react', () => {
  const result = reverse('react')
  assert.strictEqual(result, 'tcaer')
})
test('reverse of saippuakauppias', () => {
  const result = reverse('saippuakauppias')
  assert.strictEqual(result, 'saippuakauppias')
})

随后我们就可以通过命令 npm test 进行测试,这个命令会自动的找到 .test.js 文件进行测试
对于测试文件,我们也可以通过 describe 来对测试进行分组,这样我们就可以更好的对测试进行分类

const { test, describe } = require('node:test')
// ...
const average = require('../utils/for_testing').average
describe('average', () => {
  test('of one value is the value itself', () => {
    assert.strictEqual(average([1]), 1)
  })
  test('of many is calculated right', () => {
    assert.strictEqual(average([1, 2, 3, 4, 5, 6]), 3.5)
  })
  test('of empty array is zero', () => {
    assert.strictEqual(average([]), 0)
  })
})

# 接下来是示例

让我们对博客列表应用添加新功能

# mostBlogs 函数返回拥有博客最多的作者

const mostBlogs = (blogs) => {
    const authors = blogs.reduce((acc, blog) => {
        if (acc[blog.author]) {
            acc[blog.author] += 1;
        } else {
            acc[blog.author] = 1;
        }
        return acc;
    }, {});
    return Object.keys(authors).reduce((acc, author) => {
        if (authors[author] > acc.blogs) {
            return {author: author, blogs: authors[author]};
        }
        return acc;
    }, {author: '', blogs: 0});
}
# 接下来让我们对这个函数进行测试
describe('most blogs', () => {
    test('the author with most blogs', () => {
        const result = listHelper.mostBlogs(blogs)
        assert.deepStrictEqual(result, { author: 'Robert C. Martin', blogs: 3 })
    })
})

得到的结果将会是

most blogs
  ✔ the author with most blogs (0.7147ms)
most blogs (0.8951ms)
更新于 阅读次数