配置mock-cli

时间:2017-11-23 12:04:45

标签: javascript node.js unit-testing mocking mocha

我正在尝试使用mock-cli在clocha应用程序的mocha测试中存根process.arv。我想测试一个消息是console.logged当一个不正确的参数(“imit”)传递给process.argv(由命令定义)。

我正在尝试修改文档中的示例,但我认为我没有正确设置所有内容。

  1. 当我发表评论“stdin: require('../mocks/fakeInputStream'), // Hook up a fake input stream”时它会通过,但我知道它无法正常工作
  2. 在按下面所述运行时TypeError: sourceStream.on is not a function失败
  3. 有人能看到我错过的东西吗?

    /index.js

      var commands = ['init'];
    
      function getGitHeadArgs() {
          return process.argv.slice(2, process.argv.length);
        }
    
    if (getGitHeadArgs().length) {
      if (!commands.includes(getGitHeadArgs()[0])) {
        console.log("Silly Githead! That's not a githead command");
      }
      eval(getGitHeadArgs()[0])();
    } else {
      console.log("You didn't tell githead to do anything!");
    }
    

    /testIndex.js

    var assert = require('assert');
    var index = require('../index.js');
    var mockCli = require("mock-cli");
    
    describe("incorrect argument", function() {
    
          it("imit throws an error if an invalid command is raised", function() {
    
            var argv = ['node', '../index.js', 'imit']; // Fake argv
    
            var stdio = {
              stdin: require('../mocks/fakeInputStream'), // Hook up a fake input stream
              stdout: process.stdout, // Display the captured output in the main console
              stderr: process.stderr // Display the captured error output in the main console
            };
    
            var kill = mockCli(argv, stdio, function onProcessComplete(error, result) {
              var exitCode = result.code; // Process exit code
              var stdout = result.stdout; // UTF-8 string contents of process.stdout
              var stderr = result.stderr; // UTF-8 string contents of process.stderr
    
              assert.equal(exitCode, 0);
              assert.equal(stdout, "Silly Githead! That's not a githead command\n");
              assert.equal(stderr, '');
            });
    
            // Execute the CLI task
            require('../index.js');
    
            // Kill the task if still running after one second
            setTimeout(kill, 1000);
        });
    

1 个答案:

答案 0 :(得分:1)

  • ../mocks/fakeInputStream是否为有效路径?

  • ../mocks/fakeInputStream的对象是ReadableStream的有效实例吗?

  

GitHub可以使用source code

确保您符合captureStdin(sourceStream, callback)功能的要求。 该模块使用该功能捕获您的fakeInputStream并将其传输到captureStream