0

我有一个如下 src/example.js 的代码:

var argv = require('yargs')
.usage('service 1.\nUsage: $0 -s [host] -n [port]')
.alias('s', 'host') 
.alias('n', 'port')
.describe('host', 'Hostname to be used')
.describe('port', 'Port on which service will run')
.argv;  //--->> Can this line even be stubbed??


function a(){
    console.log(argv.host.toString());
    console.log(argv.port.toString())
}


module.exports = {a}

上面的单元测试用例,我正在尝试编写:

const chai = require('chai');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
var expect = require('chai').expect;

describe("Add service", function() {
    let roo;
    let argv;
    beforeEach(function() {
         var argv = {}
         argv.host = 'xx.xx.xx.xx';
         argv.port = '7677'
         roo = proxyquire('../src/example.js', { 'yargs' : { argv: argv}} );

    })

    it("Response should be logged", function() {
         roo.a()
    })

})

当我运行上面我得到以下错误:

Add service
1) "before each" hook for "Response should be logged"



  0 passing (8ms)
  1 failing

  1) Add service "before each" hook for "Response should be logged":
   TypeError: Cannot read property 'toString' of undefined
    at a (src/example.js:14:31)

我在这里做错了什么?

编辑:很明显,如果我写我的 src/example.js 如下:

var argv = require("yargs")
                .option('host', {
                       alias: 's',
                       demand: false,
                       describe: 'Hostname to be used',
                       default: "xx.xx.xx.xx"
                }) 
                .option('port', {
                       alias: 'n',
                       demand: true,
                       describe: "sme port",
                       default: "7677"
                })
                .help()
                .alias('help', 'h')
                .argv


function a(done){
   console.log(argv.machineHost.toString());
   console.log(argv.servicePort.toString())
   done(argv.machineHost)
}

module.exports = {a}

并编写测试用例如下:

const chai = require('chai');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
var expect = require('chai').expect;

describe("Add service", function() {
    let roo;
    let argv;
    beforeEach(function() {
         roo = proxyquire('../src/example.js', {} );

    })

    it("Response should be logged", function() {
         roo.a(function(resp){
            chai.expect(resp).to.equal("xx.xx.xx.xx")
         })
    })

})

有用!去搞清楚!这可能是因为我在 yargs 中设置了默认值。但是如果不进行上述更改,我不知道如何使其正常工作!

4

1 回答 1

0

这意味着“yargs”对象没有hostport属性。

尝试:

const chai = require('chai');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
var expect = require('chai').expect;

describe("Add service", function() {
    let roo;

    beforeEach(function() {
      roo = proxyquire('../src/example.js', { 'yargs' :  {
       host: 'xx.xx.xx.xx',
       port: '7677',
      }});
     })

    it("Response should be logged", function() {
         roo.a()
    })
})
于 2019-02-18T12:45:39.997 回答