I am trying to test my express web application using mocha and chai, but I am unable to figure out how to test the HTTP requests being handled by express. I am using ejs as my view engine so most of my route handlers look like this:
const someRouteHandlerForGETRequest = async (request, response) => {
// usually some DB queries to get data to display in view
const someQuery = await pool.query('SELECT * FROM table');
var sampleData = someQuery.rows;
response.render('ejspage', {
user: request.session.username,
sampleData: sampleData
});
}
Because of this, I believe that my response.body is just an html file / html string (using postman I was trying to see what was in the response, it appeared to just be the html for the view)
How do I test the data being passed to the ejs file (in this example; sampleData) that is being returned from the node-pg database query?
My current attempt at testing is this:
const { assert } = require('chai');
const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('../index');
chai.should();
chai.use(chaiHttp);
describe('/GET activeorders', () => {
it('it should GET active orders', (done) => {
chai.request('http://localhost:3000')
.get('/activeorders')
.end((err, res) => {
res.should.have.status(200);
done();
});
})
})
Basically the only this I can test is the response status, beyond that I can't figure out to test any of the values that are being returned from database queries.
I have also tried separating the model from the controller by removing the queries to the database from the route handler and instead having the route handler call a function that returns the results. This doesn't solve my problem though because using chai-http to test a HTTP request still doesn't give me access to the data since the route handler is simply rendering the ejs page with the data.