I am trying to create some unit tests with Mocha
and Chai
but I am unable to connect to the mysql server. Here I have my unit test:
process.env.NODE_ENV = 'test';
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../app');
let should = chai.should();
chai.use(chaiHttp);
describe('API endpoint /authenticate', function () {
before((done) => {
/* Todo: Clean up Database*/
done()
});
it('should authenticate a user given CORRECT username/password', (done) => {
let user = {
username: 'ax850',
password: 'test'
};
chai.request(server)
.post('/api/authenticate')
.send(user)
.end((err, res) => {
res.should.have.status(200);
done();
});
done();
});
});
As you can see, I am doing a POST
request. Then in the script where I handle this POST
request, I am connecting to a mySQL server like so:
const db = require('./../../db_conn');
And in the db_conn
I have:
const mysql = require('mysql');
const config = require('config.json')('./config.json');
let db;
const db_config = config.a_c.dbConfig;
function connectDatabase() {
if (!db) {
db = mysql.createConnection({
host: db_config.host,
user: db_config.user,
port: db_config.port,
database: process.env.NODE_ENV === 'test' ? db_config.db_test : db_config.db_dev,
//database: db_config.db_dev,
password: db_config.password
});
db.connect(function(err){
if(!err) {
console.log('Database is connected!');
} else {
console.log('Error connecting database!');
}
});
}
return db;
}
module.exports = connectDatabase();
However, when I run my test
command: mocha --timeout 10000
, it doesn't connect to the database. The mysql.createConnection
runs unsuccessfully but doesn't give an error either. Any ideas? This works when I run the server without testing.
答案 0 :(得分:1)
您在请求完成之前调用done
。
chai.request(server)
.post('/api/authenticate')
.send(user)
.end((err, res) => {
res.should.have.status(200);
done();
});
// this is executed before chai.request is fulfilled
done();