繁体   English   中英

如何测试使用 Rest API 的 oclif CLI

[英]How can I test oclif CLI that consumes Rest API

如何在 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);

    } }

Oclif 测试部分包含一个使用 nock模拟HTTP 请求的示例。 为了测试这一点,我会:

  1. 使用 nock 模拟您的帖子请求
  2. 如果 post 请求成功,则提示成功消息并断言
  3. 如果 post 请求失败,提示错误消息并断言

CLI 是一个用户界面,它让我在测试时更容易想到它。 因此,设计您的测试以断言 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.')
  })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM