It is my first time testing the routes in node js and I'm using mocha, supertest and chai. Here is my server.js file:
const express = require('express');
const app = express();
const path = require('path');
const http = require('http').Server(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const fs = require('fs');
//const helpers = require('./includes/helpers.js');
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../dist/chat/')));
require('./listen.js')(http);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS");
next();
});
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
MongoClient.connect(url, { poolSize: 10 }, function (err, client) {
if (err) { return console.log(err) }
const dbName = 'testdb';
const db = client.db(dbName);
require('./routes/create.js')(app, db);
require('./routes/remove.js')(app, db);
require('./routes/update.js')(app, db);
require('./routes/read.js')(app, db);
require('./routes/add.js')(app, db);
require('./routes/auth.js')(app, db);
require('./routes/search.js')(app, db);
});
And i want to test the read.js route, basically the read route returns a JSON array which has a few key/value parameters e.g. id (key), name (key) etc. this is my test.js file:
var assert = require('assert');
const express = require('express');
const app = express();
var read = require('../server/routes/read.js');
var http = require('http');
var helpers = require('./include/helpers');
//var api = require('../server/server.js');
var should = require('chai').should();
var expect = require('chai').expect;
var supertest = require('supertest');
var api = supertest('http://localhost:3000');
var request = require('supertest');
describe('The read route',()=>{
it('should be an object with valid parameters',function(done){
api.get('/api/read')
.set('Accept','application/json')
.expect(200)
.end(function(err,res){
if (err) throw err;
expect(res.body).to.not.equal(null);
expect(res.body).to.have.property('id');
done();
});
});
});
The testing works fine, the only issue is that when i run the line: 'expect(res.body).to.have.property('id')' , the test fails saying that expected [], i dont get it whats wrong, my read route returns a JSON array with parameters: {id:4,prodname:'iPhone',type'phone',description:'Nice phone'} (BTW it is returning data from mongodb) it should detect the id inside the parameter. Any help?