Node 19+TypeScript+tsx内置测试报错:找不到指定测试目录
Node 19内置测试运行器找不到TypeScript测试文件
问题描述
我正在使用Node 19开发一个基于TypeScript的小型库,采用Node内置测试运行器。相关配置如下:
tsconfig.json
{ "compilerOptions": { "baseUrl": ".", "declaration": true, "esModuleInterop": true, "lib": ["es2022", "dom"], "module": "commonjs", "outDir": "build", "resolveJsonModule": true, "strict": true, "target": "es2022" }, "include": ["./**/*.ts"], "exclude": ["./build"] }
package.json
{ "scripts": { "test": "tsc --noEmit && node --loader tsx --test test/**/*Tests.ts" }, "dependencies": { "@types/node": "18.11.9" }, "devDependencies": { "tsx": "3.11.0", "typescript": "4.8.4" } }
测试文件 ./test/someTests.ts
import assert from 'assert/strict'; import { describe, it } from 'node:test'; describe('tests', () => { it('passes', () => { assert.ok(true); }); });
执行npm run test时出现错误:
Could not find '/home/.../repository/test/**/*Tests.ts'
解决方案
问题出在npm脚本的通配符解析逻辑上:
npm默认使用系统默认shell(如Linux下的sh)执行脚本,而sh不支持**这种递归通配符。当你写test/**/*Tests.ts时,sh不会递归查找子目录的文件,反而会把**当作文件名的一部分,导致Node找不到对应文件。
你可以用以下两种方法解决:
方法1:让Node处理Glob匹配
把测试路径用双引号包裹,让shell直接将完整的Glob字符串传给Node,Node的--test参数本身支持解析Glob模式:
{ "scripts": { "test": "tsc --noEmit && node --loader tsx --test \"test/**/*Tests.ts\"" } }
方法2:指定用Bash执行脚本
如果系统已安装Bash,可以强制用Bash执行脚本,Bash原生支持**递归通配:
{ "scripts": { "test": "tsc --noEmit && bash -c 'node --loader tsx --test test/**/*Tests.ts'" } }
额外检查
确认你的测试文件路径符合规则:
- 文件位于
test目录或其子目录下 - 文件名以
Tests.ts结尾(你的someTests.ts符合要求)
内容的提问来源于stack exchange,提问作者baitendbidz
相关产品推荐
相关产品推荐

