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();
});
});
});
Related
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'm writing a simple test case for a route. I've used mocha, chai-http and sinon to check if correct page is rendered or not. This is for contact page where the user provides their info. and contact page is rendered again for now. Below is my test case :
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const ejs = require('ejs');
var app = require('../app');
var path = require('path');
var fs = require('fs');
var Contact = require('../models/contacts');
chai.use(chaiHttp);
var should = chai.should();
var expect = chai.expect;
describe('Contact', () => {
describe('/POST Contact', () => {
it('it should not POST a book without pages field', (done) => {
var spy = sinon.spy(ejs, '__express');
let contact = {
name: "my name",
msg: "my msg"
}
chai.request(app)
.post('/contact')
.send(contact)
.end((err, res) => {
console.log(res)
// / console.log(__dirname);
// console.log(__filname)
// var dir = __filename + './views/contact.ejs';
var dir = path.dirname(fs.realpathSync('./'));;
console.log(dir)
expect(spy.calledWithMatch(dir + '\views\contact.ejs')).to.be.true;
//expect(spy.calledWith(dir)).to.be.true;
spy.restore();
// Tell Mocha that our test case is done.
done();
// res.should.have.status(200);
//res.should.have.status()
// res.should.have.status(200);
// res.body.should.be.a('object');
//res.body.should.have.property('errors');
// res.body.errors.should.have.property('pages');
// res.body.errors.pages.should.have.property('kind').eql('required');
done();
});
});
});
});
The problem is i get an error response on res saying :
Failed to lookup view "contact" in views directory "C:\\Users\\My User\\Documents\\GitHub\\My Project\\test\\views
So basically it searches for view inside the test directory. Is there any way i can ask to view into the proper directory which is outside test ?
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 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?
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();
}
});
});