使用vitest运行oclif命令测试报错:command foo not found
基于Oclif的命令在Vitest中测试失败:命令找不到问题
我用Oclif开发了几个命令,使用Jest测试时完全正常,但切换到Vitest测试就失败了,怀疑是Mocking环节出了问题。
项目结构
src/ commands/ foo-cmd.ts tests/ foo-cmd.test.ts controllers/ foo-ctrl.ts
命令实现逻辑
foo-cmd.ts 基于 oclif/command 的异步 run() 方法开发,执行过程中会调用控制器的默认导出:
await foo(props);
测试代码
import foo from '../../controllers/foo-ctrl'; import { runCommand } from '@oclif/test'; vi.mock('../../controllers/foo-ctrl'); describe('foo command', () => { beforeEach(() => { vi.clearAllMocks(); }); it('runs foo command', async () => { const res = await runCommand( 'foo ./src/... [参数已省略]' ); console.log('+++ res', res); expect(res.stdout).toContain('Updates foo'); expect(foo).toHaveBeenCalledWith( expect.objectContaining({ ...props [参数已省略] }) ); }); //...
报错信息
测试中打印的res日志显示如下错误:
+++ res { error: CLIError: command foo not found at Config.runCommand // ... oclif: { exit: 2 }, // ... stderr: '', stdout: '' }
Vitest配置
我的vitest.config.ts相关配置如下:
test: { globals: true, environment: 'node', watch: false, disableConsoleIntercept: true },
更新补充
即使使用一个简单的Oclif+Vitest示例仓库中的测试案例,也同样无法正常运行。
内容的提问来源于stack exchange,提问作者gkri
相关产品推荐
相关产品推荐

