Oclif 提示测试

jsp*_*pru 7 unit-testing prompt command-line-interface node.js oclif

我正在尝试为包含简单提示的 Oclif 挂钩编写单元测试。我想测试钩子的输出,给出对提示的“Y”或“N”响应。

import {Hook} from '@oclif/config'
import cli from 'cli-ux'

const hook: Hook<'init'> = async function () {

  const answer = await cli.prompt("Y or N?")

  if(answer === 'Y') {
    this.log('yes')
  }
  else {
    this.log('no')
  }
}

export default hook
Run Code Online (Sandbox Code Playgroud)

我正在使用此处描述的“fancy-test”和“@oclif/test”测试框架:https ://oclif.io/docs/testing

我试过存根提示和模拟标准输入,但都没有工作 - 存根函数不可用或输出是空字符串。

这是一个测试的尝试(不起作用,因为“cli.prompt 不是函数”):

import {expect, test} from '@oclif/test'
import cli from 'cli-ux'
import * as sinon from 'sinon';

describe('it should test the "configure telemetry" hook', () => {
  test
  .stub(cli, 'prompt', sinon.stub().resolves('Y'))
  .stdout()
  .hook('init')
  .do(output => expect(output.stdout).to.contain('yes'))
  .it()
})
Run Code Online (Sandbox Code Playgroud)

我突然想到我可能没有正确构建我的测试。如果有人能指出我正确的方向或提供一些关于如何测试上述钩子的伪/示例代码,那就太棒了 - 谢谢!

Hub*_*ber 7

您是否尝试过:

import {expect, test} from '@oclif/test'
import cli from 'cli-ux'
import * as sinon from 'sinon';

describe('it should test the "configure telemetry" hook', () => {
  test
  .stub(cli, 'prompt', () => async () => 'Y')
  .stdout()
  .hook('init')
  .do(output => expect(output.stdout).to.contain('yes'))
  .it()
})
Run Code Online (Sandbox Code Playgroud)

存根.stub(cli, 'prompt', () => async () => 'Y')为我工作