node.js - Oclif 提示测试

标签 node.js unit-testing command-line-interface prompt oclif

我正在尝试为包含简单提示的 Oclif Hook 编写单元测试。我想测试 Hook 的输出,给出对提示的“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

我已尝试对提示进行 stub 并模拟标准输入,但两者均无效 - stub 函数不可用或输出为空字符串。

这是对一项测试的尝试(不起作用,因为“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()
})

我突然想到我可能没有正确地构建我的测试。如果有人能给我指出正确的方向或提供一些伪代码/示例代码来说明如何测试上述钩子(Hook),那将是非常棒的 - 谢谢!

最佳答案

你试过吗:

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 .stub(cli, 'prompt', () => async () => 'Y') 对我有用

关于node.js - Oclif 提示测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56797392/

相关文章:

javascript - Datalabels 插件 chartjs 显示 '[object]' 而不是值

unit-testing - 无法为类 LoginService 创建模拟。非接口(interface)类型的模拟需要 CGLIB 库..?

java - 嵌入式 jetty ServletTester 提供单个静态文件

ios - 提升中的项目模板

java - 我可以区分 org.apache.commons.cli 中的短选项和长选项吗

php - Symfony 控制台 - 覆盖默认选项

javascript - Node.js 运行这个小 js 文件时出现以下错误

node.js - 如何确定我的哪些依赖项取决于我的 node_modules 中的特定包?

javascript - 如何使用 Express 和 AngularJS 打开带有请求的新链接

python - 如何通过运行单元测试引用我的设置文件?