首页 > 解决方案 > 使用 Mocha 运行测试也会启动主程序

问题描述

我正在尝试使用 Mocha 来测试 CLI 应用程序。测试运行良好,但是当我启动测试程序时,它也会启动主应用程序:

$ npm run test

> standardize-js@0.2.2 test C:\Users\Gaspard\Documents\Code\standardize-js
> mocha "./source/**/*.spec.js"

? Choose your project language or framework (Use arrow keys) //<-- THIS IS THE PROGRAM
> Javascript 
  Typescript 
  AngularJS 

  Main function //<-- THIS IS THE TEST
    ask if the configuration is valid
Configuration is not valid, terminating program.
      √ should return false if the configuration is not accepted


  1 passing (29ms)

我对测试世界有点陌生,我真的很难理解我做错了什么。
这是用于启动 mocha 的 NPM 脚本:

"test": "mocha \"./source/**/*.spec.js\""

这是我的测试方法:

/* eslint-disable func-names */
const { expect } = require("chai");

const main = require("./index").test;

describe("Main function", function() {
  describe("ask if the configuration is valid", function() {
    it("should return false if the configuration is not accepted", function() {
      const fakeAnswer = false;

      expect(main.validateConfiguration(fakeAnswer)).to.equal(false);
    });
  });
});

这是我的index.js文件:

function validateConfiguration(answer) {
  if (answer === false) {
    console.log(chalk.red("Configuration is not valid, terminating program."));
    return false;
  }
  return true;
}

const run = async () => {
//MAIN FUNCTION
};

run();

// Export functions and variables to be able to test
exports.test = {
  validateConfiguration
};

标签: javascriptnode.jsmocha.js

解决方案


这不是摩卡咖啡的问题。现在只是 node.js 模块工作。

当你这样做时:

const main = require("./index").test;

Node.js 将执行index.js然后检查module.exports. 如果模块 ( index.js) 设置或修改module.exports,则节点将导出它以供require(). 但请注意,为了让节点知道模块已导出任何内容,它必须执行 javascript 文件。

Node.js 没有任何解析和分析 javascript 语法的能力(这是 V8 的工作)。与 C 或 Java 等其他语言不同,node.js 中的模块不是在语法级别实现的。因此,node.js 不需要修改 javascript 语言(例如 ES6 模块)来支持模块。模块被简单地实现为一种设计模式。

在您的 index.js 文件中,您调用运行:

run();

因此,当require()加载index.js时,它也会run()被调用。


测试库,不是主要的

解决方案是将您自己的逻辑实现为模块并对其进行测试,而不是测试index.js

mylib.js

function validateConfiguration(answer) {
  if (answer === false) {
    console.log(chalk.red("Configuration is not valid, terminating program."));
    return false;
  }
  return true;
}

// Export functions and variables to be able to test
exports.test = { validateConfiguration };

index.js

const validateConfiguration = require("./mylib").test;

const run = async () => {
    //MAIN FUNCTION
};

run();

您现在可以使用编写的测试脚本。

你怎么能不测试代码?

在不进行测试的情况下保持index.js错误的策略是删除其中的所有逻辑,除了将所有其他代码连接在一起以运行应用程序的最少代码量。代码应该像“Hello World”一样简单。这样,main 中的代码非常小而且非常简单,你可以用你的眼球来测试它的错误。

任何index.js导致错误的代码都应该重构到自己的库中,以便可以单独测试。有少数极端情况,例如加载环境变量或打开端口 80,您无法真正分离到库中,因为它们实际上是接线逻辑。对于这种情况,您只需要非常小心。


推荐阅读