Ubuntu Runner中**通配符无法展开致CI测试失败问题
问题描述
在package.json中配置了如下测试命令:
"test": "node --test --enable-source-maps --loader ts-node/esm lib/**/*.test.ts && node --test index.test.js"
该命令在本地可正常运行,但在GitHub Actions的CI环境中执行失败,报错信息如下:
yarn run v1.22.21 $ node --test --enable-source-maps --loader ts-node/esm lib/**/*.test.ts && node --test index.test.js Could not find '/home/runner/work/assert-raisins/assert-raisins/lib/**/*.test.ts'
可见**通配符未被正常展开。尝试添加shopt -s globstar命令后仍无效,完整Workflow YAML配置如下:
name: Node.js CI on: push: branches: [ "master" ] pull_request: branches: [ "master" ] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup node uses: actions/setup-node@v3 with: cache: 'npm' - run: yarn - name: Run tests run: yarn test
解决方案
方法一:强制使用bash执行命令
yarn默认使用sh执行脚本,而sh不支持globstar(即**通配符)。可以通过以下两种方式指定bash环境:
- 修改
package.json中的测试命令,明确用bash包裹:
"test": "bash -c 'node --test --enable-source-maps --loader ts-node/esm lib/**/*.test.ts && node --test index.test.js'"
- 在Workflow的测试步骤中直接用bash执行:
- name: Run tests run: bash -c "yarn test"
方法二:用Node.js的glob模块处理通配符
不依赖shell的通配符展开,直接用Node.js的glob模块扫描测试文件:
- 先安装glob依赖:
yarn add glob --dev
- 创建测试运行脚本
test-runner.js:
import { glob } from 'glob'; import { spawnSync } from 'child_process'; async function runTests() { const libTestFiles = await glob('lib/**/*.test.ts'); const allTestFiles = [...libTestFiles, 'index.test.js']; spawnSync('node', ['--test', '--enable-source-maps', '--loader', 'ts-node/esm', ...allTestFiles], { stdio: 'inherit' }); } runTests();
- 修改
package.json中的测试命令:
"test": "node test-runner.js"
方法三:在Workflow中配置bash并开启globstar
在GitHub Actions的测试步骤中指定shell为bash,并预先开启globstar选项:
- name: Run tests run: | shopt -s globstar yarn test shell: bash
内容的提问来源于stack exchange,提问作者artemave
相关产品推荐
相关产品推荐

