How to write unit tests for Inquirer.js?

孤街醉人 提交于 2019-12-05 09:41:21

You simply mock or stub any functionality that you don't want to test.

  • module.js - simplified example of a module you want to test

    const inquirer = require('inquirer')
    
    module.exports = (questions) => {
      return inquirer.prompt(questions).then(...)
    }
    
  • module.test.js

    const inquirer = require('inquirer')
    const module = require('./module.js')
    
    describe('test user input' () => {
    
      // stub inquirer
      let backup;
      before(() => {
        backup = inquirer.prompt;
        inquirer.prompt = (questions) => Promise.resolve({email: 'test'})
      })
    
      it('should equal test', () => {
        module(...).then(answers => answers.email.should.equal('test'))
      })
    
      // restore
      after(() => {
        inquirer.prompt = backup
      })
    
    })
    

There are libraries to help with mocking/stubbing, like sinon.

Also it was easier to mock inquirer.prompt in this case because .prompt was just a property on the main export inquirer which will refer to the the same object in both module.js and module.test.js. For more complicated scenarios there are libraries that can help, like proxyquire. Or you can create your modules in a way that help you switch out the dependencies easily for testing. For example:

  • module.js - make it a "factory" function which returns your main function with dependencies injected either automatically (via default arguments) or manually.

    module.exports = ({
      inquirer = require('inquirer'),
    } = {}) => (questions) => {
      return inquirer.prompt(questions).then(...)
    }
    
  • module.test.js

    const module = require('./module.js')
    
    describe('test user input' () => {
    
      const inquirer = {prompt: () => Promise.resolve({email: 'test'})};
    
      it('should equal test', () => {
        module({inquirer})(...).then(answers => answers.email.should.equal('test'))
      })
    })
    

Using inquirer.js with jest testing framework

  1. Mock inquirer
  2. Mock .prompt with response

module-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' });
  });
});

(Using ES6 or TypeScript syntax.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!