josemigallas josemigallas - 3 years ago 79
Node.js Question

How to perform nodeJS integration tests with Jasmine?

I have a server app written in nodeJS that serve as a REST Api. For unit testing I use Jasmine and I would like to perform some integration tests as well with some mock data. Tests like this one:

import ApiTestClient from "../support/api-test-client";

import User from "../../src/model/user";

describe("GET /users", () => {

it("returns an array with all users", done => {
.then(users => {
.catch(err => fail(err));


With normal unit tests I simply can mock the API calls but in this case I must first run the server app, opening 2 terminals, one for
npm start
and then another for
npm test

So far I've tried adding this pretest script to the

"pretest": "node dist/src/server.js &"

So the process runs in the background, but it doesn't feel right since it will be running after the test suite ends.

How can I start/stop the server application automatically in order to run this integration tests?

Answer Source

I found an easy way to do it using beforeEach to start express before the suite.

note: This was tested on jasmine 2.6.0 and express 4.15.3

Minimal example:

const express = require('express')
const app = express()

app.get('/world', function (req, res) {
  res.send('Hello World!')

app.get('/moon', function (req, res) {
  res.send('Hello Moon!')

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')

var request = require("request");

describe("GET /world", function() {
  beforeEach(function() {
    //we start express app here

  //note 'done' callback, needed as request is asynchronous
  it("returns Hello World!", function(done) {
    request("http://localhost:3000/world", function(error, response, html){
      expect(html).toBe("Hello World!");

  it("returns 404", function(done) {
    request("http://localhost:3000/mars", function(error, response, html){


After running it with jasmine command it returns the expected:

Example app listening on port 3000!

2 specs, 0 failures
Finished in 0.129 seconds

And server is closed (and port 3000 is closed also)

I hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download