3

I've read i can run mocha test in an Express application (nodeJS) with super test and therefore it is not required to run the app in a different terminal session. Whatever i try it always ends with a connection error.

To configure our continuous integration it is evident the integration and unit test (mocha, supertest, should) should be able to run without the node server is also running

The written tests are to validate our app's internal api end points Who can explain how to run the tests without running the express server of the app so they can be integrated with for example strider

Peter Van de Put
  • 878
  • 10
  • 26

1 Answers1

7

You need to split out your production code that calls app.listen and make sure that does not get executed during a mocha test run. I put all of my routes and settings code in app/index.js and then have a separate file app/server.js that has just a tiny bit of code to start listening, connect to the database, etc. But most of my application details are configured in app/index.js so I can test them with supertest.

//index.js
var app = require("express")();

app.get("/", function (req, res) {
  res.type("text");
  res.send("Welcome home");
});

module.exports = app;

//server.js
#!/usr/bin/env node
var app = require("./index");
app.listen(3000);

//index.mocha.js
var app = require("./index");
var request = require("supertest")(app);
var expect = require("expectacle");

describe("the home page", function () {
  it("should welome me in plain text", function(done) {
    request.get("/")
      .expect(200)
      .expect("Content-Type", "text/plain; charset=utf-8")
      .end(function (error, result) {
        expect(error).toBeFalsy();
        expect(result.text).toBe("Welcome home");
        done();
      });
  });
});
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • 1
    thanks for the feedback. can you share a same app/server.js file and app/index.js as you are using? – Peter Van de Put Aug 25 '14 at 13:41
  • Does this still run an Express process listening on some supertest-specified port, or does everything run in one process? (i.e., if I run a debugger on index.mocha.js, can I step into my Express app code?) – Greg Wilson Apr 09 '17 at 17:00
  • Yes, the server listens on an ephemeral port (OS selects an available high port). It's all one node process (both the supertest client and the express server run in the same process). Yes, you can debug it and step through the code. – Peter Lyons Apr 09 '17 at 18:05