GitLab CI移除Docker启动selenium镜像遇npx缺失问题求助
解决方案:解决selenium镜像缺少npx/php的问题
方案一:自定义包含所需依赖的镜像
基于官方selenium镜像构建自己的镜像,预安装Node.js(含npx)、PHP、Composer等依赖,避免每次CI运行重复安装。
Dockerfile示例
FROM selenium/standalone-chrome:latest # 切换root用户安装依赖 USER root # 安装Node.js和npm RUN apt-get update && apt-get install -y curl \ && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \ && apt-get install -y nodejs \ && npm install -g npm@latest # 安装PHP和Composer RUN apt-get install -y php-cli php-mbstring php-xml php-curl \ && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer # 切回seluser用户(符合selenium镜像的安全规范) USER seluser
修改后的CI配置
将镜像替换为你推送至镜像仓库的自定义镜像:
test-dev: stage: test image: your-registry/custom-selenium-chrome:latest # 替换为你的镜像地址 script: - mkdir -p tests/js/screens/diffs - npx mocha tests/js/screenshots-* --timeout 50000 - npx playwright test tests/js/pw_* - php artisan test artifacts: when: always name: $CI_COMMIT_SHA untracked: true paths: - tests/js/screens - tests/js/report cache: when: always paths: - storage/framework - vendor/ #composer packages - node_modules - public key: files: - vendor/ #composer packages - composer.lock tags: - test_new_runner
方案二:CI脚本中临时安装依赖
直接在CI运行时安装所需工具,无需维护自定义镜像,但每次运行会增加耗时。
test-dev: stage: test image: selenium/standalone-chrome script: - mkdir -p tests/js/screens/diffs # 以root权限安装Node.js、PHP和Composer - sudo apt-get update && sudo apt-get install -y nodejs npm php-cli php-mbstring php-xml php-curl curl - sudo curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer # 安装项目依赖 - npm install - composer install # 执行测试 - npx mocha tests/js/screenshots-* --timeout 50000 - npx playwright test tests/js/pw_* - php artisan test artifacts: when: always name: $CI_COMMIT_SHA untracked: true paths: - tests/js/screens - tests/js/report cache: when: always paths: - storage/framework - vendor/ #composer packages - node_modules - public key: files: - vendor/ #composer packages - composer.lock tags: - test_new_runner
注意:需确保CI runner允许sudo操作,或修改镜像默认用户为root(不推荐)。
方案三:使用GitLab CI服务配置
保留含Node.js和PHP的基础镜像,将selenium作为独立服务引入,实现环境分离。
test-dev: stage: test image: php:8.2-cli-node # 选择内置Node.js和PHP的镜像,或自定义基础镜像 services: - name: selenium/standalone-chrome alias: selenium script: - mkdir -p tests/js/screens/diffs # 配置测试工具连接selenium服务 - export SELENIUM_HOST=selenium - npm install - composer install - npx mocha tests/js/screenshots-* --timeout 50000 - npx playwright test tests/js/pw_* - php artisan test artifacts: when: always name: $CI_COMMIT_SHA untracked: true paths: - tests/js/screens - tests/js/report cache: when: always paths: - storage/framework - vendor/ #composer packages - node_modules - public key: files: - vendor/ #composer packages - composer.lock tags: - test_new_runner
需确保你的测试脚本支持通过环境变量配置selenium服务地址。
内容的提问来源于stack exchange,提问作者Miekrif
相关产品推荐
相关产品推荐

