Cannot get node js test to fail - node.js

my file structure is like this
folder_main
-server.js
-folder_tests
--serverTest.js
var expect = require("chai").expect;
var http = require('http')
describe('/', function(){
var server;
beforeEach(function () {
server = require('../server');
});
afterEach(function () {
server.close();
});
it('should return 200 status code', function(){
http.get("http://localhost:8080", function(res) {
console.log("Got response: " + res.statusCode);
expect(res.statusCode).to.equal("This isnt even a number")
})
})
})
and server.js is
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var port = 8080;
server.listen(port);
console.log("listening on port " + port)
// router
app.get('/', function (req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("Hello World\n");
});
module.exports = server;
when I run "mocha test" from the cmd line I get
✓ should return 200 status code
1) "after each" hook
1 passing (277ms) 1 failing
1) / "after each" hook:
Uncaught Error: connect ECONNRESET
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
I am confused
The first test should fail because it compares to "This isnt even a number".
I am not sure what is happening with Uncaught Error: connect ECONNRESET

Mocha tests need to use the done() callback if you are testing asynchronous code otherwise mocha will complete before your assertions run and no failures will be detected.
it('should return 200 status code', function(done){
http.get("http://localhost:8080", function(res) {
console.log("Got response: " + res.statusCode);
expect(res.statusCode).to.equal("This isnt even a number")
done()
})
})
done is setup as the first parameter to your testing function, which you then call after your assertions. If the done function is not called, mocha will timeout the test after the default of 2 seconds.
This will probably resolve your ECONNRESET issue too as your server is not being shutdown mid test/request.
It can help to always make use of done(), even when testing synchronous code so you don't fall into this trap in the future. False positives can cause hours of trouble shooting pain.

Related

Uncaught AssertionError: expected 404 to equal 405

I'm trying to test a server I have running. What I need to do is perform mocha testing on the response that the server gives. I am very new to this, so please forgive any errors that have been made.
Test is supposed to be passing, however it is not. I am very new to this, so I have not tried any alternative solutions. Thank you.
In Index.js I have:
console.log('index.js executing!');
var express = require('express');
var app = express();
app.get('/', function(req,res) {
res.send('Hello, World!');
});
app.get('/', function(req,res){
res.send('status.METHOD_NOT_ALLOWED');
});
var port = 3000;
app.listen(port,function() {
console.log('Listening on port ' + port);
});
And I am testing it with mocha :
console.log('test/test.js executing');
const chai = require('chai');
const expect = chai.expect;
const request = require('superagent');
const status = require('http-status');
const apiRoot = 'http://localhost:3000/';
describe('hello API', function(){
it('GET request returns text "Hello, World!".',function(done){
request.get(apiRoot)
.end(function(err,res){
expect(err).to.not.be.an('error');
expect(res.statusCode).to.equal(status.OK);
expect(res.text).to.equal('Hello, World!');
done();
});
});
it('POST request is not allowed',function(done){
request.post(apiRoot)
.end(function(err,res){
expect(err).to.be.an('error');
expect(res.statusCode).to.equal(status.METHOD_NOT_ALLOWED);
done();
});
});
});
The test is expected to pass.
The actual result that I am getting is:
Uncaught AssertionError: expected 404 to equal 405
+ expected - actual
-404
+405
at /home/plc/cs2410/test/test.js:26:27
at Request.callback (node_modules/superagent/lib/node/index.js:826:3)
at IncomingMessage.parser (node_modules/superagent/lib/node/index.js:1036:18)
at endReadableNT (_stream_readable.js:1129:12)
at processTicksAndRejections (internal/process/next_tick.js:76:17)
Lines 26 and 27 are:
expect(res.statusCode).to.equal(status.METHOD_NOT_ALLOWED);
done();
You're getting a 404 because your Express server is not listening for a POST to that endpoint. If you look, you've defined two GETs for that endpoint. You're also responding to the second request with a string that says status.METHOD_NOT_ALLOWED, not an actual 405 status code. You need to change your second app.get to something like this:
app.post('/', function(req,res){
res.send(405, 'Method Not Allowed');
});

Set accepted CA list and ignore SSL errors with chai-http

I'm trying to write unit tests for my node code with chai/chai-http. Everything was working fine until I switched my server to an HTTPS server, but because my certificate is signed by an internal company root and the common name of the certificate I'm using doesn't match localhost, chai is throwing an error on my request.
I'd like to do the following:
Ignore SSL errors related to domain name verification.
Set the list of CAs to check against. If this cannot be done, I'd be fine with just skipping all client-side certificate checks instead.
My code is as follows:
var chai = require('chai');
var chaiHttp = require('chai-http');
var https = require('https');
var fs = require('fs');
var server = require('../app.js');
chai.should();
chai.use(chaiHttp);
https.globalAgent.options.ca = [
fs.readFileSync('./ssl/Root.cer'),
];
describe('Attachments', function () {
it('should succeed when passed valid arguments', function (done) {
chai.request(server)
.get('/10881057300D0A4E8E8586542AA3626E41')
.set('userId', 'user')
.set('region', 'US')
.end(function (err, res) {
chai.assert(res);
res.should.have.status(200);
chai.assert(res.body);
done();
});
});
it('should return error without userId header', function (done) {
chai.request(server)
.get('/10881057300D0A4E8E8586542AA3626E41')
.end(function (err, res) {
chai.assert(res);
res.should.have.status(500);
chai.assert(res.type == 'application/json');
done();
});
});
});
And I get the following stack trace:
Uncaught AssertionError: Unspecified AssertionError
at test\test.js:21:18
at Test.Request.callback (node_modules\superagent\lib\node\index.js:615:12
)
at ClientRequest.<anonymous> (node_modules\superagent\lib\node\index.js:56
7:10)
at TLSSocket.socketErrorListener (_http_client.js:267:9)
at emitErrorNT (net.js:1253:8)
I solved it by the suggestion here.
I think it is rejecting as invalid TLS. Even though mine was not using an invalid cert, I assume somewhere in the guts it is changing the valid cert's url to localhost or resolving to an IP address which isn't associated to the FQDN of the cert I am using. Adding the following code before the first "describe()" fixed it for me.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
Here is the full test code:
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../server');
var should = chai.should();
chai.use(chaiHttp);
// This line allows use with https
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
describe('Auth', function() {
it('should return 401 with invalid credentials', function(done){
chai.request(server)
.post('/api/v1/user/authenticate')
.send({"email":"badaccount#somedomain.com", "password": "password"})
.end(function(err, res) {
res.should.have.status(401);
done();
});
});
});

How to test app connection with express, nodeJS and Mocha

I've got my app properly configured, such that if I run node app.js everything starts up. I'm trying to test for the connection of my app is working properly using unit tests. What I have so far is:
var options = {
url: 'http://localhost',
port: 8080,
};
var app = require("../app.js");
var should = require('should');
var assert = require("assert");
var async = require('async');
it ('tests the ok connection of the app by checking that it is listening on port 8080', function(dont) {
request(options,app)
.get('/')
.expect(200)
.end(function (err, res) {
res.header['location'].should.include('/')
res.text.should.include('Listening on port 8080');
done();
});
});
I was getting the error message Error: options.uri is a required argument, which is why I added the var options. Now I'm getting error message TypeError: Object #<Request> has no method 'get'.
How can properly check that I have a good connection (200), that i'm on the right page ('/') and that it is logging the message Listening on port 8080 upon connection?
Thanks!
For the TypeError, make sure you are using supertest and not something else like request. The reason for this is that the module request does not provide the .expect() and other functions.

connect ECONMREFUSED when using MOCHA to SUPERTEST an express app

I am using MOCHA to test some express framework code.
I have written a simple MOCHA code to test messages returned in the response header. The code works. It also means that I am connected to the server and I can get the file from the database.
Now, I want to use "SuperTest" to do the same thing. But, I get "Error: connect ECONMREFUSED"
Here is my code:
var express = require('express');
var request = require('supertest');
var app = express();
describe('GET /core/dbq/534e930204dd311822ec1c9d', function() {
this.timeout(15000);
it ('Check header message', function(done) {
request(app)
.get('http://localhost:3001/ecrud/v1/core/dbq/534e930204dd311822ec1c9d')
.expect('warning', '100 Max Record Limit Exceeded')
.expect('Content-Type', /json/)
.expect(200, done);
} )
} )
and the error showing on the console is:
1) GET /core/dbq/534e930204dd311822ec1c9d Check header message:
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
I am learning to use "SuperTest". Please help. Thank you.
Supertest starts the application on a random port and fills the host+port part of the URL for you. Your code should supply the path (and query) part only.
request(app)
.get('/ecrud/v1/core/dbq/534e930204dd311822ec1c9d')
// etc.
.expect(200, done);
Alternatively, you can start the application yourself before running the test.
describe('GET /core/dbq/534e930204dd311822ec1c9d', function() {
this.timeout(15000);
before(function(done) {
app.listen(3001, function() { done(); });
});
it ('Check header message', function(done) {
request(app)
.get('http://localhost:3001/ecrud/v1/core/dbq/534e930204dd311822ec1c9d')
// etc.
});
});
I would highly recommend going with the first approach, otherwise your tests may clash with other applications listening on port 3001.

Issues using BusterJS, ExpressJS, and SuperTest

I'm having some issues testing routes using ExpressJS + BusterJS + SuperTest.
var app = require("../../app/app.js"),
buster = require("buster"),
expect = buster.referee.expect,
http = require('http'),
request = require('supertest');
buster.spec.expose();
describe("V2 API - group/get", function () {
var server;
beforeEach(function() {
server = http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
});
it("is accessable", function() {
request(server)
.get('/')
.expect(200)
.end(function(err, res){
server.close();
expect(err).toBe(null);
});
});
});
When I run this test, I get:
Failure: V2 API - group/get is accessible
No assertions!
1 test, 0 assertions, 1 runtime ... 1 failure
Express server listening on port 3000
Which seems wrong, because I actually do have an assertion. The problem is that it doesn't get called unless there is an error.
Another issue is that if I have multiple 'if' blocks, the server doesn't restart between them. I might be using the node + express + buster + supertest stack wrong, so any help with how to test these routes would be greatly appreciated.
I have some code that doesn't have your problem; it does almost the same thing as yours but with asynchronous tests, e.g.
it("is accessable", function(done) {
request(server)
.get('/')
.expect(200)
.end(function(err, res){
server.close();
expect(err).toBe(null);
done();
});
});
I don't know enough about Buster to know if this is the "right way" to fix this issue, but hope it helps!

Resources