Jest测试中@ts-expect-error指令失效问题求助
使用NX和Axiom开发Express应用时,在Jest测试中使用//@ts-expect-error指令,终端与编辑器均提示“Unused '@ts-expect-error' directive”错误。TypeScript版本为4.9.5,尝试开启checkJS后问题仍未解决。
测试代码:
describe('apps', () => { it('should return an error if you return things not in the ts definition', () => { expect(() => { appNotify.get('/v1/notify/healthcheck', (res) => { //@ts-expect-error - notExistingProperty shold not be allowed res.json({ notExistingProperty: true, message: 'Welcome to notify! ' }); }); }).toThrow(); }); });
tsconfig配置:
{ "compileOnSave": false, "compilerOptions": { "rootDir": ".", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2015", "module": "esnext", "lib": ["es2017", "dom"], "skipLibCheck": true, "skipDefaultLibCheck": true, "baseUrl": ".", "paths": { "@notify/logger": ["libs/logger/src/index.ts"], "@notify/notify-redis-client": ["libs/notify-redis-client/src/index.ts"] }, "strict": true }, "exclude": ["node_modules", "tmp"] }
解决思路
确认类型错误真实存在
//@ts-expect-error仅在下方代码确实触发TypeScript编译错误时生效,否则会提示“未使用”。Express默认的Response.json()方法接受any类型参数,所以当前代码不会触发类型错误。若要让参数类型严格,需给res指定带泛型的Response类型,比如res: Response<ExpectedDataType>,这样传入包含notExistingProperty的对象才会触发类型检查错误。区分编译时类型检查与运行时异常
测试逻辑expect(() => {...}).toThrow()是检测运行时抛出的异常,但TypeScript类型错误属于编译时检查,不会在运行时抛出。如果要验证类型约束,应该用类型测试工具(如tsd),而非Jest的运行时断言。检查NX测试文件的专属tsconfig
NX项目中,测试文件通常对应tsconfig.spec.json配置,而非根目录的tsconfig.json。确认该配置文件中开启了strict、noUnusedLocals等类型检查选项,确保TypeScript能检测到预期的错误。修正指令格式与拼写
将指令调整为规范格式:// @ts-expect-error - notExistingProperty should not be allowed(添加空格、修正shold拼写为should),虽然这不是核心问题,但规范格式能避免潜在的解析问题。
内容的提问来源于stack exchange,提问作者Jurgo Boemo

