charliebrownie charliebrownie -4 years ago 276
Javascript Question

Mocha API Testing: getting 'TypeError: app.address is not a function'

My Issue

I've coded a very simple CRUD API and I've started recently coding also some tests using
but I'm having an issue when running my tests with
$ mocha

When I run the tests I get the following error on the shell:

TypeError: app.address is not a function

My Code

Here is a sample of one of my tests (/tests/server-test.js):

var chai = require('chai');
var mongoose = require('mongoose');
var chaiHttp = require('chai-http');
var server = require('../server/app'); // my express app
var should = chai.should();
var testUtils = require('./test-utils');


describe('API Tests', function() {
before(function() {
mongoose.createConnection('mongodb://localhost/bot-test', myOptionsObj);

beforeEach(function(done) {
// I do stuff like populating db

afterEach(function(done) {
// I do stuff like deleting populated db

after(function() {

describe('Boxes', function() {

it.only('should list ALL boxes on /boxes GET', function(done) {
.end(function(err, res){

// the rest of the tests would continue here...



And my
app files (/server/app.js):

var mongoose = require('mongoose');
var express = require('express');
var api = require('./routes/api.js');
var app = express();

mongoose.connect('mongodb://localhost/db-dev', myOptionsObj);

// application configuration

// routing set up
app.use('/api', api);

var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;

console.log('App listening at http://%s:%s', host, port);

and (/server/routes/api.js):

var express = require('express');
var boxController = require('../modules/box/controller');
var thingController = require('../modules/thing/controller');
var router = express.Router();

// API routing
router.get('/boxes', boxController.getAll);
// etc.

module.exports = router;

Extra notes

I've tried logging out the
variable in the /tests/server-test.js file before running the tests:

var server = require('../server/app'); // my express app

console.log('server: ', server);

and I the result of that is an empty object:
server: {}

Answer Source

You don't export anything in your app module. Try adding this to your app.js file:

module.exports = server
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download