Hello
This question is about Personal Library Project
if NODE_ENV=test
,app returning 404 for all routes.If I comment out runner.run();
in server.js
,then everything works fine.
I am suspecting my code in server.js is not compatible with testrunner code.
Is there anyway I could resolve this issue?
server.js
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const myDB = require('./db.js');
const apiRoutes = require('./routes/api.js');
const fccTestingRoutes = require('./routes/fcctesting.js');
const runner = require('./test-runner');
const app = express();
app.use('/public', express.static(process.cwd() + '/public'));
app.use(cors({origin: '*'})); //USED FOR FCC TESTING PURPOSES ONLY!
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
myDB(async (client) => {
const myDataBase = await client.db('myFirstDatabase');
//Index page (static HTML)
app.route('/')
.get(function (req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
//For FCC testing purposes
fccTestingRoutes(app);
//Routing for API
apiRoutes(app,myDataBase);
//404 Not Found Middleware
app.use(function(req, res, next) {
res.status(404)
.type('text')
.send('Not Found');
});
})
//Start our server and tests!
let PORT = process.env.PORT || 3000;
app.listen(PORT, function () {
console.log("Listening on port " + PORT);
if(process.env.NODE_ENV==='test') {
console.log('Running Tests...');
setTimeout(function () {
try {
runner.run();
} catch(e) {
let error = e;
console.log('Tests are not valid:');
console.log(error);
}
}, 1500);
}
});
module.exports = app; //for unit/functional testing
db.js
require('dotenv').config();
const { MongoClient } = require('mongodb');
async function main(callback) {
const URI = process.env.MONGO_URI; // Declare MONGO_URI in your .env file
const client = new MongoClient(URI, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// Connect to the MongoDB cluster
await client.connect();
// Make the appropriate DB calls
await callback(client);
} catch (e) {
// Catch any errors
console.error(e);
throw new Error('Unable to Connect to Database')
}
}
module.exports = main;