简体   繁体   中英

How to run mocha test file from an npm scripts command?

I'm following the Mocha test docs to setup a unit test on some API routes. In order to this I set up a \\test dir containing index.test.js. Installed packages required by the test file including mocha . Then specified the command to run mocha in package.json, npm test :

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

But when I run npm test from within the test directory containing index.test.js. The test doesn't seem to run and just show me:

在此处输入图片说明

I also referred to this Stackoverfow answer to no avail - Configure node npm package.json so that "npm test" works on both unix and windows

Question:

How can you run a mocha test file from npm script?

This is the directory location of the test file - C:\\Users\\brianj\\Documents\\Projects\\WebService-for-Self-service-Metrics-Portal\\test\\index.test.js

This is the actual test file from \\test called index.test.js with required packages already installed prior to calling 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;
        });
       }); //
    }
  });
});

Can you try npm run test, if you are one dir above of the test directories? Or if you are in the test dir then you can try npm run ../test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM