我在使用 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并回车,测试用例就会通过.
现在我想自动化该过程,我应该做什么?
最佳答案
首先,我不明白无限 while 循环内需要“query.getNumber”。
let choice = query.getNumber("plz choice from(1~3):");//waiting for user's
如果删除此功能,您可以使用一些机器人节点模块来实现此目的。 检查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
关于javascript - 如何在 NodeJS 单元测试中模拟用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45793713/