Oclif提示测试

8

我试图为一个包含简单提示的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

我正在使用这里描述的'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()
})

我意识到我的测试可能没有正确地进行结构化。如果有人能指点我正确的方向或提供一些伪代码/示例代码来测试上述钩子,那就太棒了 - 谢谢!

1个回答

9

您尝试过以下方式吗:

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()
})

使用.stub(cli, 'prompt', () => async () => 'Y')对我起了作用


如果您有任何指针,关于如何捕获在发出警告后继续的数据 this.warn(message: string | Error),感谢您提前。 - lAH2iV
1
仅从代码片段很难确定。 我在尝试登录 oclif 时也遇到了问题。 也许你可以提一个单独的问题? - st.huber
它适用于多个提示吗? - Souvik De
你可以在 async (input) => { return 'Y'} 中编写一个函数,并根据提示返回不同的值。 - st.huber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接