Debian上JS自动化测试配置指南
一 环境准备
sudo apt update && sudo apt install -y nodejs npm,安装后用 node -v、npm -v 验证版本。curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
二 单元测试配置 Jest
npm init -y
npm install --save-dev jest
jest.config.js):module.exports = {
testEnvironment: 'node', // 或 'jsdom' 用于前端代码
verbose: true,
collectCoverage: true,
coverageDirectory: 'coverage',
testMatch: ['**/*.test.js', '**/*.spec.js'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
}
};
sum.js:function sum(a,b){ return a+b; }; module.exports = sum;__tests__/sum.test.js:const sum = require('../sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
package.json:"scripts": { "test": "jest" }npm test(或 npx jest)。三 E2E网页自动化配置 Cypress
npm install --save-dev cypress
npx cypress open
npx cypress run四 持续集成与本地运行
name: Node.js CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x]
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm test -- --ci
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo apt update && sudo apt install -y jenkins
sudo systemctl enable --now jenkins
pipeline {
agent any
tools { nodejs 'node-20' } // 在“全局工具配置”预先定义 node-20
stages {
stage('Checkout') { steps { git 'https://github.com/your/repo.git' } }
stage('Install') { steps { sh 'npm ci' } }
stage('Test') { steps { sh 'npm test -- --ci' } }
}
}
npm testnpx cypress opennpx cypress run。