javascript - How to mocking user input in unit test in NodeJS? -


i'm running problems when writing unit test code using mochajs. here code:

//index.js var query = require('cli-interact');// helper tools interacting synchronously user @ command line.   module.exports = function main() {     while (true){     let choice = query.getnumber("plz choice from(1~3):");//waiting user's input;     }     if(choice === 3){       console.log("you entered 3");     } //...other code }  //test_spec.js var chai = require("chai"); var sinon = require("sinon"); var sinonchai = require("sinon-chai"); var expect = chai.expect; chai.use(sinonchai); var main = require("../index.js"); describe("test input ", function(){     sinon.spy(console, 'log');      it("enter 3", function(){         main();         //now test code block here, want automatically input 3,but don't know how.         let result = console.log.calledwith("you entered 3")         expect(result).to.equal(true);     });  }); 

as code shows above, when run test case, terminal shows line "plz choice from(1~3):" , waiting input, once type 3 , enter, test case pass.

now want automate process, should do?

first don't understand need of 'query.getnumber' inside infinite while loop.

let choice = query.getnumber("plz choice from(1~3):");//waiting user's 

if removed, can use robo node modules achieve this. check robotjs https://www.npmjs.com/package/robotjs

index.js

 var query = require('cli-interact');     let main = () => {         let choice;         while (choice != 3) {             choice = query.getnumber("plz choice from(1~3):");              console.log('your choice : ' + choice);             if (choice === 3) {                 console.log("you entered 3");             }         }     };     module.exports = main; 

test_spec.js

var chai = require("chai"); var sinon = require("sinon"); var sinonchai = require("sinon-chai"); var expect = chai.expect; chai.use(sinonchai); var main = require("../index.js"); var robot = require("robotjs");  var roboinput = (input) => {     robot.typestring(input);     robot.keytap("enter"); }; var roboinputarr = (inputs) => {     inputs.foreach(ip =>{         roboinput(ip);     }); }; describe("test input ", function() {     sinon.spy(console, 'log');     it("enter 3", function() {         roboinputarr([1,2,3]);         main();         let result = console.log.calledwith("you entered 3")         expect(result).to.equal(true);     }); }); 
test input -----------  enter 3:  plz choice from(1~3):1  choice : 1  plz choice from(1~3):2  choice : 2  plz choice from(1~3):3  choice : 3  entered 3  pass 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -