i am using Express js and Mysql for my application, now i want to start unit testing. I have written this code:
var request = require('supertest');
var server = require('./app');
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('./app');
var should = chai.should();
chai.use(chaiHttp);
describe('loading express', function () {
it('responds to /', function testSlash(done) {
request(server)
.get('/')
.expect(200, done);
});
it('404 everything else', function testPath(done) {
request(server)
.get('/foo/bar')
.expect(404, done);
});
it('responds to /customers/getCustomerData', function testPath(done) {
request(server)
.get('/customers/getCustomerData?id=0987654321')
.end(function(err, res){
res.should.have.status(200);
res.body.should.be.a('object');
res.body.status.should.equal("success");
res.body.data.customerId.should.equal("0987654321");
done();
});
});
});
This code is working properly but it makes connection to database and checking all the test cases which i have written, but this is called integration testing i have to do unit testing using mock database. How can i achieve this mocking of database?
Related
I want to run tests on my node express server however this application is starting the server like this:
createServer()
.then(server => {
server.listen(PORT);
Log.info(`Server started on http://localhost:${PORT}`);
})
.catch(err => {
Log.error("Startup failure.", { error: err });
process.exit(1);
});
and I know the chai.request() needs to have a parameter that is pointing toward the server app, how can I export/import this createServer() function and pass it in the request method of the chai object?
You can use require.main to distinguish between your files being run directly by Node or imported as modules.
When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require.main === module.
E.g.
server.js:
const express = require('express');
const PORT = 3000;
async function createServer() {
const app = express();
app.get('/', (req, res) => {
res.send('hello world');
});
return app;
}
if (require.main === module) {
createServer()
.then((server) => {
server.listen(PORT);
console.info(`Server started on http://localhost:${PORT}`);
})
.catch((err) => {
console.error('Startup failure.', { error: err });
process.exit(1);
});
}
module.exports = { createServer };
When you import the createServer from the server.js file, the if statement block will not execute. Because you want to create the server instance in the test case.
server.test.js:
const { createServer } = require('./server');
const chai = require('chai');
const chaiHTTP = require('chai-http');
const { expect } = require('chai');
chai.use(chaiHTTP);
describe('70284767', () => {
it('should pass', async () => {
const server = await createServer();
chai
.request(server)
.get('/')
.end((err, res) => {
expect(err).to.be.null;
expect(res.text).to.be.equal('hello world');
});
});
});
I'm using mocha, chai, and sinon to test some authenticated API routes. I'm using passport.authenticate() as middleware to authenticate the route:
const router = require('express').Router();
const passport = require('passport');
router.post('/route',
passport.authenticate('jwt', {session:false}),
function(req,res) {
return res.status(200);
});
module.exports = router;
Then, in my test suite, I am using sinon to stub out passport.authenticate calls:
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
const server = require('../../app');
const expect = chai.expect;
chai.use(chaiHttp);
describe('route', function() {
before(function(done) {
sinon.stub(passport, 'authenticate').callsFake(function(test, args) {
console.log('Auth stub');
});
console.log('stub registered');
passport.authenticate('jwt', {session:false});
done();
});
after(function(done) {
console.log('after hook');
passport.authenticate.restore();
done();
});
describe('POST /route', function() {
it('should post', function(done) {
console.log('starting test');
chai.request(server)
.post('/route')
.end(function(err,res) {
expect(res).to.have.status(200);
done();
});
});
});
});
Now, when I run the test suite, I see it print out the following:
route
stub registered
Auth stub
POST /route
starting test
1) should post
after hook
1 failing
1) route
POST /route
should post:
Uncaught AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 401
From this, we can see that the after the stub is registered, I can call it in the test file and it is properly stubbed. But when passport.authenticate() is called in route.post(), it is the actual passport.authenticate() and sends a response with status 401 because I'm not authenticated.
Any thoughts on what's going on?
Your code calls passport.authenticate as soon as it runs, and it runs as soon as it is required.
Because you are requiring the code at the beginning of the test before the stub has been created your code ends up calling the real passport.authenticate.
In order for code like this to call the stub you must set up your stub before you require your code:
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
// const server = require('../../app'); <= don't require your code here...
const expect = chai.expect;
chai.use(chaiHttp);
describe('route', function () {
before(function (done) {
sinon.stub(passport, 'authenticate').callsFake(function (test, args) {
console.log('Auth stub');
});
console.log('stub registered');
passport.authenticate('jwt', { session: false });
done();
});
after(function (done) {
console.log('after hook');
passport.authenticate.restore();
done();
});
describe('POST /route', function () {
it('should post', function (done) {
console.log('starting test');
const server = require('../../app'); // <= require it AFTER creating the stub
chai.request(server)
.post('/route')
.end(function (err, res) {
expect(res).to.have.status(200);
done();
});
});
});
});
One small note related to sinon stubbing, I manage to have it working using this syntax:
passport.authenticate = sinon.stub( passport, 'authenticate' )
.returns(
( req, res, next ) => {
const user = {
username: 'test user',
email: 'testuser#mail.com',
displayName: 'Test User',
provider: 'testCase',
roles: [ 'admin' ]
}
req.user = user;
next()
}
);
Main things are:
add user data into req.user
execute next() for code flow to continue into next middleware
To recap this is not a way to actually test your authentication strategy but to bypass it in case you want to test router results.
I am trying to write a unit test for the following file named a.js
var express = require('express');
var router = express.Router();
router.get('/getHCQ', function (req, res) {
res.send("OK");
});
module.exports = router;
Unit test file : a.spec.js
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var a = require('./a');
describe('Unit Test', function () {
it('should run this', function (done) {
chai.request(a)
.get('/getHCQ')
.end(function(err, res) {
res.should.have.status(200);
done();
});
});
});
I am running it using Mocha but getting the following error :
Uncaught TypeError: Cannot read property 'apply' of undefined
at Immediate.<anonymous> (node_modules/express/lib/router/index.js:635:14)
Can someone please help me to figure out what am I doing wrong here?
Perhaps you forgot to configure chai with chai-http
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
chai.use(chaiHttp); // <-- add this
var a = require('./a');
describe('Unit Test', function () {
it('should run this', function (done) {
chai.request(a)
.get('/getHCQ')
.end(function(err, res) {
res.should.have.status(200);
done();
});
});
});
Getting error Uncaught TypeError: Cannot read property 'apply' of undefined
at Immediate. (node_modules/express/lib/router/index.js:618:14)
Server and test files.
// server js file
'use strict';
var express = require('express'); // call express
var app = express();
var port = process.env.PORT || 8080;
// Routes for schedule API
var router = express.Router();
router.get('/', function(req, res, next) {
res.json({"msg":'Hello, World!'});
});
app.listen(port);
console.log('Application running on port ' + port);
module.exports=router;
// test.js
var chai = require('chai');
var chaiHttp=require('chai-http');
var server = require('../server');
var should = chai.should();
chai.use(chaiHttp);
describe('Scheduler', function () {
it('should return hello world', function (done) {
chai.request(server)
.get('/')
.end(function (err, res) {
res.should.have.status(200);
done();
};
});
});
Could anybody help me to track what went wrong here?
You can use expect instead of should it's more easier
var chai = require('chai'), chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
app.get('/check', function(req, res) {
//exemple
expect(req.query.ip,"IP Adress Mismatch").to.be.an.ip;
}
I use chai module to test code.
var CONFIG = require('./config');
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var server = CONFIG.apiPath;
chai.use(chaiHttp);
describe('TEST', function() {
it('getAllLandingPage completed',function(){
chai.request(server)
.get('getAllLandingPage')
.end(function(err, res){
res.should.have.status(200);
console.log('res: ', res) // not show
done();
});
});
});
I want console.log(res) to show result so I can to know function right or wrong
It seems you miss done in the callback function of it, try it as below
it('getAllLandingPage completed',function(done){
chai.request(server)
.get('getAllLandingPage')
.end(function(err, res){
if (err)
done(err);
else {
res.should.have.status(200);
console.log(res)
done();
}
});
});