如何在NodeJS中单元测试中模拟用户输入?

时间:2017-08-21 09:31:12

标签: javascript mocha

使用mochaJS编写单元测试代码时遇到了一些问题。这是我的代码:

//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);
    });

});

如上面的代码所示,当我运行测试用例时,终端显示一行“plz choice from(1~3):”并等待我的输入,一旦我输入3并输入,测试用例将通过

现在我想自动化这个过程,我该怎么办?

1 个答案:

答案 0 :(得分:2)

首先,我不了解“query.getNumber'在无限循环中。

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

如果删除它,您可以使用一些robo节点模块来实现此目的。 检查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