Mongoose open connection issue with Supertest - javascript

I am unable to run multiple Supertest/Mocha tests as I get an error Error: Trying to open unclosed connection. - I found this post which suggest looping and checking connection status. Wondering if there is a better way? perhaps something that was added in Supertest recently to handle this.

In your Mocha tests add a before function to connect to MongoDB like so
var mongoose = require('mongoose');
describe('My test', function() {
before(function(done) {
if (mongoose.connection.db) return done();
mongoose.connect('mongodb://localhost/puan_test', done);
});
});

Ok - was pretty close. What I had to do was remove the describe method call and place a before() call in a common file to all tests - supertest or just straight mocha unit tests.
var db;
// Once before all tests - Supertest will have a connection from the app already while others may not
before(function(done) {
if (mongoose.connection.db) {
db = mongoose.connection;
return done();
}
db = mongoose.connect(config.db, done);
});
// and if I wanted to load fixtures before each test
beforeEach(function (done) {
fixtures.load(data, db, function(err) {
if (err) throw (err);
done();
})
});
By omitting the describe() call the above it makes it available to all tests.

// Also you can use the 'open' event to call the 'done' callback
// inside the 'before' Mocha hook.
before((done) => {
mongoose.connect('mongodb://localhost/test_db');
mongoose.connection
.once('open', () => {
done();
})
.on('error', (err) => {
console.warn('Problem connecting to mongo: ', error);
done();
});
});

Related

Mocha Error: ENOENT: no such file or directory, scandir './tests'

So I'm new in QA Testing, is learning in freecodecamp right now and got this code for the challenge. I've tried some TDD unit testing and worked. But when I tried a functional testing, I always got an error. Here is my code inside 2_functional-tests.js:
const chai = require('chai');
const assert = chai.assert;
const server = require('../server');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
suite('Functional Tests', function () {
this.timeout(5000);'use strict'
suite('Integration tests with chai-http', function () {
// #1
test('Test GET /hello with no name', function (done) {
chai
.request(server)
.get('/hello')
.end(function (err, res) {
assert.fail(res.status, 200);
assert.fail(res.text, 'hello Guest');
done();
});
});
// #2
test('Test GET /hello with your name', function (done) {
chai
.request(server)
.get('/hello?name=xy_z')
.end(function (err, res) {
assert.fail(res.status, 200);
assert.fail(res.text, 'hello xy_z');
done();
});
});
// #3
test('Send {surname: "Colombo"}', function (done) {
chai
.request(server)
.put('/travellers')
.end(function (err, res) {
assert.fail();
done();
});
});
// #4
test('Send {surname: "da Verrazzano"}', function (done) {
assert.fail();
done();
});
});
});
const Browser = require('zombie');
suite('Functional Tests with Zombie.js', function () {
this.timeout(5000);
suite('Headless browser', function () {
test('should have a working "site" property', function() {
assert.isNotNull(browser.site);
});
});
suite('"Famous Italian Explorers" form', function () {
// #5
test('Submit the surname "Colombo" in the HTML form', function (done) {
assert.fail();
done();
});
// #6
test('Submit the surname "Vespucci" in the HTML form', function (done) {
assert.fail();
done();
});
});
});
I'm running the code test using this command:
mocha --ui tdd 2_functional-tests.js
But I get an error of ENOENT: no such file or directory, scandir './tests'. I've tried to install all the required module and tried solution from any forum such clearing cache, deleting npm_modules folder, etc. I also installed all the required module from another required file, like in ('../server') (line 4). But still got no luck. Unfortunately, I could run this code in replit.com. I'm using VS Code and got the error.
Any helpful response would be very appreciated!

Mocha tests timeout although the post client works well

I always get this error
Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
idk what's wrong with mocha tests hope someone helps (the post client works tho)
controller.js
module.exports.get_post_tags = (req, res) => {
PostTag.find({})
.then(tags => res.json(tags))
.catch(err => {
console.error(err)
res.send('An error happened while getting the data please try again later')
})
}
api.js
// #method GET
// #route /api/posttag
// #desc get all post tags
router.get('/posttags', get_post_tags)
unit_tests.js
describe('PostTag', function() {
it('Get all post tags', function(done) {
chai.request(app)
.get('/api/posttags')
.end((err, res) => {
expect(res).to.have.status(200)
done()
});
});
}

express, mocha testing always returns 404

My express POST route is:
app.post("/addPost", function(req, res) {
let newComment = { post: req.body.createP, comment: req.body.createC };
myDB.push(newComment);
res.render("index.ejs", { posts: myDB });
});
And my mocha test
describe("POST /", function() {
it("it ", function(done) {
supertest(myApp.app)
.post("/")
.expect(200)
.end(function(err, res) {
if (err) return done(err);
done();
});
});
});
Manually, the POST route works fine, but the mocha test always returns 404 instead of 200. Also, the mocha test for GET routes does work. Any ideas whats causing this?
Plus, how would one test html form data being sent via a POST request. Thanks in advance!

Can't add templating engine in plugin HapiJS

I want to implement routes per plugin, but I can't add the views engine inside the plugin. I've seen examples where this is possible, E.G.: https://github.com/hapijs-edge/hapi-plugins.com/blob/master/lib/routes.js, but I'm getting an error saying server.views is not a function
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection();
var myPlugin = {
register: function (server, options, next) {
// Error happens here, should be able to see server.views()
console.log(server.views());
next();
}
};
myPlugin.register.attributes = {
name: 'myPlugin',
version: '1.0.0'
};
server.register( myPlugin, function(err) {
if (err) {
console.error('Failed to load a plugin:', err);
}
} );
server.start(function () {
console.log('Server running at:', server.info.uri);
});
It seems to be a problem with hapi v10. Try "npm i hapi#8.8.1", that version should work
The guys at hapi, showed me the way... as of hapi 9, vision module is required to decorate server and have access to the views method. It now works fine!
You need to register vision plugin before you can use server.view function as of hapi => 9.x.x.

NodeJs Server Request Testing

For testing my NodeJs Server I am using mocha and supertest.
But I don`t like the simplicity of my tests, they actually are not checking server properly.
// simple test
describe('Server GET requests', function() {
it('GET /index', function(done){
request(app)
.get('/')
.expect(200, done)
})
})
So the test is only checking that server has a response for the request, but is not checking the correctnes of the response. I want test to be looking something like this:
// test should be
describe('Server GET requests', function() {
it('GET /index', function(done){
request(app)
.get('/')
.expect(200)
.end(function (err, res) {
if (err != null)
done(err);
checkContentTitle('Home Page', res.text);
checkContent(params, res.text);
done();
})
})
})
// function to check the title of the send result
function checkContentTitle(title, htmlText){
// checkTitle(title, parse('title', htmlText));
}
But I can`t find the propriate way of doing this.
What is a good practice of testing server responses, GET-request responses for example?
I suppose I need some tols like html\DOM parser, to get specific tags? Can somebody advise proper tools?
Try the cheerio library:
cheerio
It works like jquery for selecting DOM elements, very easy to use.
You can compare the cheerio returned values with the assertions that you want.
Example of test/test.js:
var assert = require("assert");
var cheerio = require('cheerio');
var request = require('request');
describe('domtesting', function() {
describe('GET /', function () {
it('title must be Hello', function (done) {
request('http://example.com/',function(err,response,html){
if(!err){
var $ = cheerio.load(html);
assert.equal('Hello', $('title').text());
done();
}
else{
console.log(err);
}
})
});
});
});
Use named functions or mocha promise syntax in order to get more readable and maintainable code. I also used the request library for launch http request inside tests.

Categories