如何从npm脚本命令运行mocha测试文件?

时间:2017-01-23 16:20:03

标签: node.js express automated-tests mocha

我跟随Mocha test docs在某些API路线上设置单元测试。 为此,我设置了一个包含index.test.js的\test目录。测试文件所需的已安装软件包,包括mocha。然后指定在package.json中运行mocha的命令npm test

"scripts": {
    "test": "mocha ./test",
    "start": "node index.js"
  },

但是当我从包含index.test.js的测试目录中运行npm test时。测试似乎没有运行,只是告诉我:

enter image description here

我也提到这个Stackoverfow的答案无济于事 - Configure node npm package.json so that "npm test" works on both unix and windows

问题:

如何从npm脚本运行mocha测试文件?

这是测试文件的目录位置 - C:\Users\brianj\Documents\Projects\WebService-for-Self-service-Metrics-Portal\test\index.test.js

这是来自\test的实际测试文件,名为index.test.js,在调用mocha之前已经安装了所需的包:

var chai = require('chai');
var should = chai.should();
var sinon = require('sinon');
var request = require('supertest');
var _  = require('lodash');
var express = require('express');
var app = express();



// Global array to store all relevant args of calls to app.use
var APP_USED = []

// Replace the `use` function to store the routers and the urls they operate on
app.use = function() {
  var urlBase = arguments[0];

  // Find the router in the args list
  _.forEach(arguments, function(arg) {
    if (arg.name == 'router') {
      APP_USED.push({
        urlBase: urlBase,
        router: arg
      });
    }
  });
};

// GRAB all the routes from our saved routers:
_.each(APP_USED, function(used) {
  // On each route of the router
  _.each(used.router.stack, function(stackElement) {
    if (stackElement.route) {
      var path = stackElement.route.path;
      var method = stackElement.route.stack[0].method.toUpperCase();

      console.log(method + " -> " + used.urlBase + path);

      describe(method + " -> " + used.urlBase + path, function() {
      request(app)
        .get(used.urlBase + path)
        .expect('Content-Type', /json/)
        .expect(200, "ok")
        .end(function(err, res){
           if (err) throw err;
        });
       }); //
    }
  });
});

1 个答案:

答案 0 :(得分:0)

如果您比测试目录高1个目录,可以尝试npm run test吗? 或者,如果您在测试目录中,则可以尝试npm run ../test