我正在尝试为一个包含简单提示的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
我使用的是这里描述的“花式测试”和“@oclif/ test”测试框架:https://oclif.io/docs/testing
我尝试了存根提示符和模拟stdin,但两者都不起作用-要么存根函数不可用,要么输出是空字符串。
下面是一个测试的尝试(因为'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()
})
我突然想到,我可能没有正确地组织我的测试。如果有人能给我指出正确的方向,或者提供一些伪/样本代码,告诉我如何测试上面的钩子,那就太棒了-谢谢!
发布于 2019-07-01 21:46:31
你有没有尝试过:
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')进行存根对我来说很有效
https://stackoverflow.com/questions/56797392
复制相似问题