我有一个如下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中设置了默认值。但我不知道如何做才能在不做上述更改的情况下使它起作用!
答案 0 :(得分:0)
这意味着'yargs'对象没有host
或port
属性。
尝试:
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()
})
})