I am writing test cases for my node js code but the test case is failing with errors. I do not have write access to the test scripts so I need to fix my nodejs code itself. I want to solve this using http module instead of express so this is my code.
This is my node js code:
var http = require('http');
const requestListener = function (req, res) {
let url = req.url;
let method = req.method;
let valid = false;
let ar = url.split("/");
let id = 0;
if(method == 'GET') {
if(ar.length == 3) {
valid = true;
}
}
if(valid) {
res.setHeader("Content-Type", "application/json");
res.writeHead(200);
res.end(`{"message": "Project found"}`);
} else {
res.setHeader("Content-Type", "application/json");
res.writeHead(404);
res.end(`{"message": "Not Found"}`);
}
return;
};
const host = 'localhost';
const port = 8000;
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
This is my test code :
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../index');
const Promise = require('bluebird');
const should = chai.should();
chai.use(chaiHttp);
describe('sample', () => {
it('Should return 404 for wrong path', (done) => {
chai.request(server)
.get('/')
.then(response => {
response.status.should.eql(404);
done()
})
});
When I run this test case I am getting error as :
✓ Should return 404 for wrong path
(node:7739) UnhandledPromiseRejectionWarning: AssertionError: expected 200 to deeply equal 400
at /projects/test/index.spec.js:25:40
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:7739) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7739) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I see a tick mark on test case name ✓ which I am assuming as correct, but I still see errors printing on output.
How to fix this errors?
Also with postman
tool I can see 404 status code and message :project not found as JSON format which is expected output for loalhost:8000/