在 CentOS 上测试 Node.js 项目的完整流程
一 环境准备与版本管理
- 建议使用 NVM 管理 Node.js 版本,便于多版本切换与隔离:
- 安装与启用:
- yum 安装 git:sudo yum install -y git
- 克隆并启用 nvm:git clone https://github.com/cnpm/nvm.git ~/.nvm && cd ~/.nvm && git checkout
git describe --abbrev=0 --tags
- echo “. ~/.nvm/nvm.sh” >> /etc/profile && source /etc/profile
- 常用命令:nvm ls-remote、nvm install v14.17.0、nvm use v14.17.0、nvm alias default v14.17.0
- 也可使用二进制包安装(示例):
- wget https://nodejs.org/dist/v14.17.0/node-v14.17.0-linux-x64.tar.xz
- tar -xvJf node-v14.17.0-linux-x64.tar.xz
- ln -s /root/node-v14.17.0-linux-x64/bin/node /usr/local/bin/node
- ln -s /root/node-v14.17.0-linux-x64/bin/npm /usr/local/bin/npm
- 验证:node -v、npm -v
- 国内环境可设置 npm 镜像源 提升安装速度:npm config set registry https://registry.npmmirror.com
二 测试类型与常用工具
- 单元测试:验证最小单元(函数、类、模块)的正确性,推荐 Jest / Mocha + Chai / Tape / Tap。
- 集成测试:验证多个模块/服务协作,常用 Supertest 对 HTTP 接口发起请求,配合内存数据库或测试替身。
- 端到端测试(E2E):模拟真实用户操作,推荐 Cypress / Selenium。
- 覆盖率与质量:使用 Istanbul(nyc)生成覆盖率报告;配合 ESLint 做静态检查。
三 快速上手示例
- 示例一 Mocha + Chai(适合已有项目渐进引入)
- 安装依赖:npm i -D mocha chai
- 在 package.json 添加脚本:
{
“scripts”: { “test”: “mocha ‘test/**/*.js’ -R spec” }
}
- 编写测试 test/math.test.js:
const { expect } = require(‘chai’);
const { add } = require(‘…/math’);
describe(‘math.add’, () => {
it(‘should return 3 when adding 1 and 2’, () => {
expect(add(1, 2)).to.equal(3);
});
});
- 运行:npm test
- 示例二 Jest(开箱即用,适合新项目)
- 安装:npm i -D jest
- 配置 package.json:
{
“scripts”: { “test”: “jest” },
“jest”: { “testEnvironment”: “node” }
}
- 编写测试 math.test.js:
const { add } = require(‘./math’);
test(‘adds 1 + 2 to equal 3’, () => {
expect(add(1, 2)).toBe(3);
});
- 运行:npm test
- 示例三 Supertest 接口测试(Express 示例)
- 安装:npm i -D supertest
- 假设 app.js 导出 express 实例:
const request = require(‘supertest’);
const app = require(‘./app’);
describe(‘GET /’, () => {
it(‘should return 200 and hello’, async () => {
const res = await request(app).get(‘/’);
expect(res.statusCode).toBe(200);
expect(res.text).toContain(‘Hello’);
});
});
- 运行:npm test
四 覆盖率与静态检查
- 覆盖率(Istanbul/nyc)
- 安装:npm i -D nyc
- 运行:npx nyc npm test(或 npx nyc mocha)
- 生成 HTML 报告:npx nyc --reporter=html npm test,报告位于 coverage/ 目录
- 静态检查(ESLint)
- 初始化:npx eslint --init,按需选择框架与风格
- 检查:npx eslint .
五 运行与持续集成
- 本地运行
- 监听模式:在 package.json 增加脚本 “test:watch”: “mocha --watch” 或 “test:watch”: “jest --watch”,保存即测
- 持续集成(GitHub Actions 示例 .github/workflows/ci.yml)
- name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: ‘14’ }
- run: npm ci
- run: npm test – --ci
- run: npx nyc report --reporter=text-lcov | npx coveralls
- 说明:若使用 Jenkins / Travis CI 等,也可按相同思路配置脚本与报告上传