Peter Van de Put
Peter Van de Put

Reputation: 938

test express API requires local server

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

Upvotes: 3

Views: 3694

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146034

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

Upvotes: 7

Related Questions