繁体   English   中英

Jest的单元测试查询者

[英]Unit testing Inquirer with Jest

我一直在试图了解搜索各种论坛的内容,但是无法找到我想要的内容。 部分是由于我对NodeJS的无知。 我刚开始。

我的任务是通过Jest / Mocha对基于查询者的CLI进行单元测试。 我该如何模拟和测试。

我的cli.js看起来像这样-

var inquirer = require('inquirer');

var question = {
  name: 'name',
  message: 'Enter your name : '
};

inquirer
.prompt([question])
.then (function(response) {
    console.log(JSON.stringify(response))
    }
);

如果我只是要确保用户传递的值不能超过10个字符,那么我该如何编写测试。

有人可以指出通过Jest我的单元测试代码将是什么(当然使用任何模拟包)。

在此先感谢您的帮助 !

Cli.js

const inquirer = require('inquirer');

const validateNameResponse = response => response.length <= 10;
const handleAnswers = answers = {
// whatever you want to do with answers
};

const question = {
  type: 'input',
  name: 'name',
  message: 'Enter your name : ',
  validate: validateNameResponse
};

inquirer
.prompt([question])
.then (handleAnswers);

module.exports = {
  validateNameResponse,
};

Cli.unit.test.js(Cli.unit.test是同一目录中的兄弟文件)

const {
  validateNameResponse,
} = require('./cli');
describe('cli', () => {

  for(let i =0; i <= 10; i++;) {
    it(`should have function validateNameResponse pass inputted name that is ${i} characters long`, () => {
      const name='a'.repeat(i);
      expect(validateNameResponse(name)).toBe(true)
    });
  }

  it('should have function validateNameResponse fail inputted name that is more than 10 characters', () => {
    const name = 'a'.repeat(11);
    expect(validateNameResponse(name)).toBe(false);
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM