javascript - 配置模拟客户端

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

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

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

  1. 当我注释掉“stdin: require('../mocks/fakeInputStream'),//Hook up a fake input stream”时它通过了,尽管我知道它不能正常工作
  2. 按如下所述运行时失败并显示 TypeError: sourceStream.on is not a function

有人能看到我错过了什么吗?

/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);
    });

最佳答案

  • ../mocks/fakeInputStream 是有效路径吗?

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

The source code is avalible at GitHub.

确保满足 captureStdin(sourceStream, callback) 函数的要求。 该模块使用该函数来捕获您的 fakeInputStream 并将其通过管道传输到 captureStream

关于javascript - 配置模拟客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47455178/

相关文章:

javascript - 循环并组合每两个项目

javascript - Rails 4 ajax 处理为 html

javascript - 解析JSON数组nodejs

node.js - 停止 Pug 中的每个循环

c# - 每次调用最小起订量时,模拟方法输出不同的输出参数

unit-testing - 如何对没有副作用的方法进行单元测试?

javascript - PHPStorm 配置 : How to remove background color on embedded html?

javascript - jquery 响应式菜单

mysql - NodeJS MySQL 高级查询

java - Gradle 编译但不运行 TestNG 测试