我想知道如何为 npm 包Inquirer.js编写单元测试,这是一个使 CLI 包更容易的工具。我已经阅读了这篇文章,但我无法让它发挥作用。
这是我需要测试的代码:
const questions = [
{
type: 'input',
name: 'email',
message: "What's your email ?",
},
{
type: 'password',
name: 'password',
message: 'Enter your password (it will not be saved neither communicate for other purpose than archiving)'
}
];
inquirer.prompt(questions).then(answers => {
const user = create_user(answers.email, answers.password);
let guessing = guess_unix_login(user);
guessing.then(function (user) {
resolve(user);
}).catch(function (message) {
reject(message);
});
} );
...这是用 Mocha 编写的测试:
describe('#create_from_stdin', function () {
this.timeout(10000);
check_env(['TEST_EXPECTED_UNIX_LOGIN']);
it('should find the unix_login user and create a complete profile from stdin, as a good cli program', function (done) {
const user_expected = {
"login": process.env.TEST_LOGIN,
"pass_or_auth": process.env.TEST_PASS_OR_AUTH,
"unix_login": process.env.TEST_EXPECTED_UNIX_LOGIN
};
let factory = new profiler();
let producing = factory.create();
producing.then(function (result) {
if (JSON.stringify(result) === JSON.stringify(user_expected))
done();
else
done("You have successfully create a user from stdin, but not the one expected by TEST_EXPECTED_UNIX_LOGIN");
}).catch(function (error) {
done(error);
});
});
});
我想用process.env.TEST_LOGIN
(回答第一个 Inquirer.js 问题)和process.env.TEST_PASS_OR_AUTH
(回答第二个 Inquirer.js 问题)填充标准输入,以查看该函数是否创建了有效的配置文件(值 unix_logincreate
由工厂对象)。
我试图了解 Inquirer.js 如何对自身进行单元测试,但我对 NodeJS 的理解还不够好。你能帮我做这个单元测试吗?