且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为Inquirer.js编写单元测试?

更新时间:2023-02-16 23:02:37

您只需模拟或存根不想测试的任何功能。

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


  • module.js -简化您要测试的模块的示例

  • 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

  • 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
      })
    
    })
    


  • 有些库可以帮助进行模拟/存根,例如 sinon

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

    在这种情况下,更容易模拟 inquirer.prompt ,因为 .prompt 只是主出口查询者上的一个属性,它将在两个模块中引用相同的对象。 js module.test.js 。对于更复杂的情况,有些库可以提供帮助,例如 proxyquire 。或者,您可以通过一种有助于您轻松切换依赖关系进行测试的方式来创建模块。例如:

    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 >-使其成为工厂函数,该函数将返回您的主函数,并带有自动(通过默认参数)或手动注入的依赖项。

    • 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

  • 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'))
      })
    })