温馨提示×

Debian上JS自动化测试如何配置

小樊
42
2025-11-25 09:57:53
栏目: 编程语言

Debian上JS自动化测试配置指南

一 环境准备

  • 安装 Node.js 与 npm(建议选择 LTS 版本):
    • 方式A(Debian仓库):执行 sudo apt update && sudo apt install -y nodejs npm,安装后用 node -vnpm -v 验证版本。
    • 方式B(NodeSource,指定版本如 20.x):执行
      curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
      sudo apt-get install -y nodejs
      
  • 建议:优先使用 Node.js LTS、配置 npm 国内镜像(如淘宝源)以加速依赖安装。

二 单元测试配置 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.jsfunction 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
    
  • 运行与配置要点:
    • 首次运行会生成 cypress 目录与示例用例,可直接在图形界面中选择浏览器执行。
    • 无头运行(CI/服务器常用):npx cypress run
    • 兼容性:支持 Debian 8+(64 位) 等主流发行版。

四 持续集成与本地运行

  • GitHub Actions 示例(Node.js):
    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
    
  • Jenkins(Debian 服务器):
    • 安装与启动:
      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
      
    • 插件建议:GitPipelineNodeJS(用于提供 Node/npm 环境)。
    • 流水线示例(Jenkinsfile):
      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 test
    • E2E 交互:npx cypress open
    • E2E 无头:npx cypress run

0