How should I run the nodejs application automatically for tests

I have a restful style nodejs service that does not have an interface, it just takes data and then does something with it.

I have a module that tested most of the method level materials that I want, but now I want to basically do some automated tests to prove that it all works together. When I use ASP.MVC and IIS, since the server is always on, so I just configure the script (insert the dummy guff in the DB), then do the HttpRequest and send it to the server and claim that I am returning what I expect.

However, there are several problems in nodejs, since applications must be run through the command line or some other mechanism, so given that I have app.js that will start listening, is there any way for me to automatically launch this before I ran my tests and then close it after completing my tests?

I am currently using Yadda with Mocha for my testing, so I can save it in BDD style, however I hope that launching the web application is an agnostic of the frameworks I use.

+4
source share
3 answers

Just release a few ways to start and stop your web server. Your app.js file could be something like this:

var app = express()
var server = null
var port = 3000

// configure your app here...

exports.start = function(cb) {
  server = http.createServer(app).listen(port, function () {
    console.log('Express server listening on port ' + port)

    cb && cb()
  })
}

exports.close = function(cb) {
  if (server) server.close(cb)
}

// when app.js is launched directly
if (module.id === require.main.id) {
  exports.start()
}

- ( mocha):

var app = require('../app')

before(function(done) {
  app.start(done)
})

after(function(done) {
  app.close(done)
})
+8

supertest https://github.com/visionmedia/supertest ,

describe('GET /users', function(){
 it('respond with json', function(done){
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);   
  }) 
 })
+1

Using gimenete's answer, here is an example of a service (server) with asynchronous wait and expression:

service.js:

const app = require('express')()
const config = require('./config')

let runningService

async function start() {
  return new Promise((resolve, reject) => {
    runningService = app.listen(config.get('port'), config.get('hostname'), () => {
      console.log('API Gateway service running at http://${config.get('hostname')}:${config.get('port')}/')
      resolve()
    })
  })
}

async function close() {
  return new Promise((resolve, reject) => {
    if (runningService) {
      runningService.close(() => {
      })
      resolve()
    }
    reject()
  })
}

module.exports = {
  start,
  close
}

service.spec.js:

const service = require('../service')

beforeEach(async () => {
  await service.start()
})

afterEach(async () => {
  await service.close()
})
0
source

All Articles