简体   繁体   English

如何测试使用 Rest API 的 oclif CLI

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

How can I test the following code build using Typescript in Oclif?如何在 Oclif 中使用 Typescript 测试以下代码构建? This CLI consumes a rest api build with node.js and express.js.此 CLI 使用带有 node.js 和 express.js 的 rest api 构建。 I am testing my api with mocha/chai which I have become familiar with.我正在用我熟悉的 mocha/chai 测试我的 api。 However, I saw the example on the oclif site about testing, but besides that there is no actual help with testing.但是,我在 oclif 站点上看到了有关测试的示例,但除此之外没有实际帮助进行测试。 How can I test the following code which is a command from my cli?如何测试以下代码,它是来自我的 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);

    } }

The Oclif Testing section includes an example of mocking an HTTP request using nock. Oclif 测试部分包含一个使用 nock模拟HTTP 请求的示例。 To test this I would:为了测试这一点,我会:

  1. Mock your post request using nock使用 nock 模拟您的帖子请求
  2. Prompt a success message if the post request is successful and assert that如果 post 请求成功,则提示成功消息并断言
  3. Prompt an error message if the post request fails and assert that too如果 post 请求失败,提示错误消息并断言

A CLI is a User Interface , it made my life easier to think of it as such when testing. CLI 是一个用户界面,它让我在测试时更容易想到它。 So design your tests to assert the CLI output and use unit tests for the business logic.因此,设计您的测试以断言 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