Simple Unit Testing NodeJS/Express

时间:2016-04-25 09:23:52

标签: javascript node.js unit-testing mocha

Hi I am pretty new to NodeJs and I am trying to write my first tests.

I am kind of stuck with the setup, so I was hoping for some help.

I wrote these two functions:

app.js:

var express = require('express')
  , cors = require('cors')
  , app = express();

app.get('/a_nice_jsonp',cors(corsOptions), function(req, res, next){
  var result = parseCookies(req);
  res.jsonp(result);
});

app.get('',function(req,res,next){
  res.statusCode = 200;
  res.end()
});

I do not export it as module as it is my only file.

I assume it's pretty easy to write the tests for that. I started with something like this:

app-test.js:

var expect = require('expect.js');
var express = require('express');
var expressApp = express();

describe('app js test', function() {
  describe('GET /', function() {
    it('should respond to GET with empty path', function () {
      expressApp.get('', function(req, res, body){
        expect(res.status).to.equal(200);
      });
    })
  });
});

I suppose it really reads like a simple task, but I seem to fail over the setup of the test and how to do it.

Can anyone help me out here?

EDIT: The above test runs fine. However, I have difficulties to test e.g. .end() as well as the result in the jsonp request. I simple do not know how to do it?!

1 个答案:

答案 0 :(得分:1)

当你这样做时

expressApp.get('', function(req, res, body){
    expect(res.status).to.equal(200);
  });

你只是映射路线。

要测试您的REST API,您必须使用像supertest这样的库(在该链接中使用express + mocha进行测试的示例)

它以这种方式工作

var request = require('supertest');
var express = require('express');

var app = express();

app.get('/a_nice_jsonp',cors(corsOptions), function(req, res, next){
  var result = parseCookies(req);
  res.jsonp(result);
});

app.get('',function(req,res,next){
  res.statusCode = 200;
  res.end()
});

describe('app js test', function() {
  describe('GET /', function() {
     it('should respond to GET with empty path', function (done) {
        request(app)
               .get('')
               .expect(200)
               .end(done) 
     });
  });
});

使用分隔文件进行编辑

app.js

var express = require('express')
  , cors = require('cors')
  , app = express();

app.get('/a_nice_jsonp',cors(corsOptions), function(req, res, next){
  var result = parseCookies(req);
  res.jsonp(result);
});

app.get('',function(req,res,next){
  res.statusCode = 200;
  res.end()
});
module.exports = app;

APP-test.js

var request = require('supertest');
var app = require('app.js');


describe('app js test', function() {
  describe('GET /', function() {
     it('should respond to GET with empty path', function (done) {
        request(app) 
               .get('')
               .expect(200)
               .end(done) 
     });
  });
});