我想知道如何为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);
});
} );...and这里是用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问题)填充stdin,以查看函数是否创建有效的配置文件(由工厂对象的方法create猜测的值unix_login )。
我试图理解Inquirer.js单元是如何测试自身的,但是我对NodeJS的理解还不够好。你能帮我做这个单元测试吗?
发布于 2018-04-16 18:00:12
您只是简单地模拟或存根任何您不想测试的功能。
module.js -要测试的模块的简化示例
查询者=要求(‘问询者’) module.exports =(问题) => {返回inquirer.prompt(问题).then(.)}module.test.js
const = require(' inquirer ') const模块= require('./module.js')描述(‘测试用户输入’) => { // stub让备份;在( () ) => { backup =inquirer.prompt之前inquirer.prompt =( => Promise.resolve({email:' test‘}) })它(’应该等于测试‘,() => {模块(.).then(答案=> answers.email.should.equal(’test‘) }) //恢复之后() => { inquirer.prompt = backup }) })有一些库可以帮助模拟/顽固性,比如西农。
而且,在本例中模拟inquirer.prompt更容易,因为.prompt只是主导出inquirer上的一个属性,它将引用module.js和module.test.js中的相同对象。对于更复杂的场景,有一些库可以提供帮助,比如丙氧奎尔。或者,您可以以一种帮助您轻松切换依赖项以进行测试的方式创建模块。例如:
module.js --使它成为一个“工厂”函数,它通过自动(通过默认参数)或手动注入依赖项返回主函数。
module.exports = ({询问者=要求(‘询问者’),}= {}) => (问题) => {返回inquirer.prompt(问题).then(.)}module.test.js
const模块= require('./module.js')描述(‘测试用户输入’) => { =>查询者={提示符:() => Promise.resolve({email:' test‘}) };它(’应该等于测试‘,() => {模块{模块({ inquirer }) (.).then(应答=>answers.email.should.equal(’test‘)})}发布于 2018-08-22 14:12:39
将inquirer.js与jest测试框架结合使用
inquirer.promptmodule-test.js
import module from './module';
import inquirer from 'inquirer';
jest.mock('inquirer');
describe('Module test', () => {
test('user input', async () => {
expect.assertions(1);
inquirer.prompt = jest.fn().mockResolvedValue({ email: 'some@example.com' });
await expect(module()).resolves.toEqual({ email: 'some@example.com' });
});
});(使用ES6或TypeScript语法。)
https://stackoverflow.com/questions/49862039
复制相似问题