如何在Oclif中使用Typescript测试以下代码构建?此CLI使用node.js和express.js的rest api构建。我正在用我熟悉的mocha/chai测试我的api。然而,我在oclif网站上看到了关于测试的例子,但除此之外,对测试并没有实际的帮助。我如何测试下面的代码,它是来自我的cli的命令?
import cli from 'cli-ux'
// just prompt for input
import {Command} from '@oclif/command'
import {createConnection} from "typeorm";
import {flags} from '@oclif/command'
const bcrypt = require('bcrypt');
var fs=require('fs');
const https = require('https')
const axios=require('axios');
const client_cert = fs.readFileSync('ca-crt.pem')
axios.defaults.httpsAgent = new https.Agent({ca : client_cert, keepAlive: true})
export class AdminCommand extends Command {
static flags = {
newuser: flags.string({dependsOn:['passw'],exclusive:['newdata','userstatus','moduser']}),
moduser: flags.string({dependsOn:['passw'],exclusive:['newuser','newdata','userstatus']}),
passw: flags.string({dependsOn:['email']}),
email: flags.string({dependsOn:['quota']}),
quota: flags.string(),
userstatus: flags.string({exclusive:['newdata','newuser','moduser']}),
newdata: flags.string({dependsOn:['source'],exclusive:['userstatus','newuser','moduser']}),
source: flags.string()
}
async run() {
const {flags} = this.parse(AdminCommand);
var fs=require('fs');
var jwt=require('jsonwebtoken');
var token = fs.readFileSync('softeng19bAPI.token','utf-8');
axios.defaults.headers.common['X-OBSERVATORY-AUTH']=token;
await cli.anykey();
//create new user
if (`${flags.newuser}` !== "undefined" && `${flags.passw}` !== "undefined" && `${flags.email}` !== "undefined" && `${flags.quota}` !== "undefined" ){
let hash = bcrypt.hashSync(`${flags.passw}`,10);
let body = new Object ({
username: `${flags.newuser}`,
passw: `${flags.passw}`,
email: `${flags.email}`,
quota: `${flags.quota}`
})
await axios.post('https://localhost:8765/energy/api/Admin/users',body);
} }
发布于 2020-07-28 23:12:00
Oclif Testing部分包含一个使用nock模拟HTTP请求的示例。为了测试这一点,我将:
命令行界面是一个用户界面,它让我在测试时更容易想到它。因此,将您的测试设计为断言CLI输出,并对业务逻辑使用单元测试。
// Success test case, assuming the command name is 'admin:create'
describe('admin', () => {
const newUser = {...}
test
.stdout()
.nock('https://localhost:8765', api =>
api
.persist()
.post('/energy/api/Admin/users')
.reply(200, newUser)
)
.command('admin:create')
.it('shows success message when user is created', ctx => {
expect(ctx.stdout).to.contain('User was successfully created.')
})
})
https://stackoverflow.com/questions/60451552
复制相似问题