Yu Duan Yu Duan - 1 month ago 13
Javascript Question

How to mocking user input in unit test in NodeJS?

I'm running some problems when writing my unit test code using mochaJS. Here is my code:

//index.js
var query = require('cli-interact');// helper tools for interacting synchronously with user at command line.

module.exports = function main() {
while (true){
let choice = query.getNumber("plz choice from(1~3):");//waiting for 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 the test code block here, I want to automatically input 3,but don't know how.
let result = console.log.calledWith("you entered 3")
expect(result).to.equal(true);
});

});


As the code shows above, when I run the test case, the terminal shows a line "plz choice from(1~3):" and waiting for my input, once I type 3 and enter, the test case will pass.

Now I want to automate the process, what should I do?

Answer Source

First I don't understand the need of 'query.getNumber' inside infinite while loop.

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

If this is removed, you can use some robo node modules to 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 is : ' + 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 
your choice is : 1 
plz choice from(1~3):2 
your choice is : 2 
plz choice from(1~3):3 
your choice is : 3 
you entered 3 
Pass