errors creating test for passport using mocha - mocha.js

I've been working a while on getting a test to work with Mocha and Passport. I tried a couple articles on here, but I can't get them to work.
Currently, I have installed supertest and I'm trying that.
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHttp = require('chai-http');
var app = require('../app');
//var request = require('supertest')//(app);
//var server = request.agent(app);
//var Strategy = require('passport-strategy');
var Strategy = require('passport-local').Strategy;
var m_ticket_data = require('../model/ticket');
var m_Kbase_data = require('../model/Kbase');
var m_KbaseScript_schema = require('../model/KbaseScript');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);
chai.use(require('chai-passport-strategy'));
describe('Ticket', function() {
var user, info;
before(function(done) {
console.log("hello from strategy");
chai.passport.use( new Strategy(function(username, password, done){
console.log("hello from strategy2");
done(null, { id: '1234' }, { scope: 'read' });
}
))
.success(function(u, i) {
user = u;
info = i;
done();
})
.req(function(req) {
//req.headers.authorization = 'Bearer vF9dft4qmT';
})
.authenticate();
done();
});
it ('blankout the database', function(done){
m_ticket_data.remove({}, function(){
done();
});
});
it('looks for a blank from /ticket/all', function (done) {
chai.request('http://127.0.0.1:5000')
.get('/ticket/all')
.end(function (err, res) {
res.status.should.equal(200);
console.log(res.body);
//expect(res.body).to.deep.equal({});
done();
});
});
});
I can't create a temp user for testing, so I was thinking I was going to have to overwrite the authentication. However, I'm having a problem doing that. I found this npm (https://github.com/jaredhanson/chai-passport-strategy), and I'm trying this as the latest.
This is a test I created that works fine. I don't need to authenticate for it.
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../app');
var m_Kbase_data = require('../model/Kbase');
var m_KbaseScript_schema = require('../model/KbaseScript');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);
describe('KBasefull', function() {
m_Kbase_data.collection.drop();
it('need to add a kbase article for testing /KBase', function (done) {
chai.request('http://127.0.0.1:5000')
.post('/kbase')
.send({Problem: "Problem", description: "Description", resolution: "Something to fix"})
.end(function(err, res){
res.should.have.status(200);
done();
});
});
}

Related

dateObj.getMonth() not working in nativescript

I am trying to get the month from the date object . But I am getiing error whci displays says "getMonth is not a function".
Since I saw some Java script tutorials , where getMonth() is supported in ES6.
Am I missing importing anything.
var config = require("../../shared/config");
var fetchModule = require("fetch");
var ObservableArray = require("data/observable-array").ObservableArray;
var datePickerModule = require("tns-core-modules/ui/date-picker");
function TaskListViewModel(items){
var listModel = new ObservableArray(items);
listModel.getTaskList = function()
{
return fetchModule.fetch(config.TaskListURL,{
method:"Get"
})
.then(handleErrors)
.then(function(response){
return response.json();
}).then(function(data) {
data.forEach(function(element) {
var dateObj = Date.parse(element.followUpDate)
listModel.push({
fallowUpDateMonth:dateObj.getMonth(),
faloowUpDateDay:dateObj.getDate(),
fallowupDateYear:dateObj.getFullYear(),
});
});
});
};
return listModel;
}
module.exports = TaskListViewModel;

ioredis bluebird a promise was created in a handler but was not returned from it

Can someone please explain to me why i'm getting this warning Warning: a promise was created in a handler but was not returned from it when I execute the following code:
cache['deviceSlave'].getBySystemId(systemId).then(function(slavesMapping) {
// do other stuff
}).catch(function(err) {
// throw error
});
Here is the rest of the code:
var Promise = require('bluebird');
var _ = require('lodash');
var Redis = require('ioredis');
var config = require('/libs/config');
var redis = new Redis({
port: config.get('redis:port'),
host: config.get('redis:host'),
password: config.get('redis:key'),
db: 0
});
var self = this;
module.exports.getBySystemId = function(systemId) {
return new Promise(function(resolve, reject) {
var systemIds = [systemId];
self.getBySystemIds(systemIds).then(function(result) {
return resolve(_.values(result)[0]);
}).catch(function(err) {
return reject(err);
});
});
};
module.exports.getBySystemIds = function(systemIds) {
return new Promise(function(resolve, reject) {
var pipeline = redis.pipeline();
_.each(systemIds, function(systemId) {
var cacheKey = 'device_slaves:' + systemId.replace(/:/g, '');
// get through pipeline for fast retrieval
pipeline.get(cacheKey);
});
pipeline.exec(function(err, results) {
if (err) return reject(err);
else {
var mapping = {};
_.each(systemIds, function(systemId, index) {
var key = systemId;
var slaves = JSON.parse(results[index][1]);
mapping[key] = slaves;
});
return resolve(mapping);
}
});
});
};
I'm using the following libraries: ioredis & bluebird.
The code executes fine and everything just works good! I just dont like the fact I get an warning which I can not solve!
Bluebird is warning you against explicit construction here. Here is how you should write the above code:
module.exports.getBySystemId = function(systemId) {
return self.getBySystemIds([systemId]).then(result => _.values(result)[0]);
};
There is no need to wrap the promise - as promises chain :)

useFakeTimers mocha chai sinon - not the right result on a test

I am trying to run a test where I want to verify that my helper file is running correctly, and if I have an expired token, I get an error kickback and cannot proceed.
I have a feeling that I can only fake the time directly in the test, and not outside of it. Thing is, I don't want to copy the jwt.verify function in my test because that defeats the purpose if I change the code in the actual helper file. Any help on this one to make this work?
I am faking the time with sinon. If I test to see what time I get now and after the clock tick, I do get the right results. But for some reason this is not applying to the function in another file.
my local.js file
const moment = require('moment');
const jwt = require('jsonwebtoken');
const secret = process.env.TOKEN_SECRET;
function encodeToken(user) {
const playload = {
exp: moment().add(1, 'hours').unix(), // expires the token in an hour
iat: moment().unix(),
sub: user.id
};
return jwt.sign(playload, secret);
}
function decodeToken(token, callback) {
const payload = jwt.verify(token, secret, function (err, decoded) {
const now = moment().unix();
console.log('tim: ' + decoded.exp); //just to see
console.log('now: ' + now); // just to see
if (now > decoded.exp) {
callback('Token has expired.');
}
callback(null, decoded);
});
}
module.exports = {
encodeToken,
decodeToken
};
and my test file:
process.env.NODE_ENV = 'test';
const chai = require('chai');
const should = chai.should();
const sinon = require('sinon');
const localAuth = require('../../src/server/auth/local');
describe('decodeToken()', function () {
var clock;
beforeEach(function () {
clock = sinon.useFakeTimers();
});
afterEach(function () {
clock.restore();
});
it('should return a decoded payload', function (done) {
const token = localAuth.encodeToken({
id: 1
});
should.exist(token);
token.should.be.a('string');
clock.tick(36001000000);
localAuth.decodeToken(token, (err, res) => {
should.exist(err);
res.should.eql('Token has expired.');
done();
});
});
});
JWT checks the expiry and throws error by itself. So we just have to assert from the error message. I have made some changes to the code and made it working.
I tested this as below, (code snippets)
const moment = require('moment');
const jwt = require('jsonwebtoken');
const secret = 'abczzxczxczxc';
function encodeToken(user) {
const payload = {
exp: moment().add(1, 'hours').unix(), // expires the token in an hour
iat: moment().unix(),
sub: user.id
};
const token = jwt.sign(payload, secret);
return token;
}
function decodeToken(token, callback) {
jwt.verify(token, secret, function(err, decoded) {
callback(err, decoded);
});
}
module.exports = {
encodeToken,
decodeToken
};
Tested as below,
process.env.NODE_ENV = 'test';
const chai = require('chai');
const should = chai.should();
const sinon = require('sinon');
const localAuth = require('./');
describe('decodeToken()', function () {
var clock;
beforeEach(function () {
clock = sinon.useFakeTimers();
});
afterEach(function () {
clock.restore();
});
it('should return a decoded payload', function (done) {
const token = localAuth.encodeToken({
id: 1
});
token.should.exist;
token.should.be.a('string');
clock.tick(36001000000);
localAuth.decodeToken(token, (err, res) => {
should.exist(err);
err.message.should.eql('jwt expired');
done();
});
});
});
Output
➜ faketimer ./node_modules/mocha/bin/mocha index_test.js
decodeToken()
✓ should return a decoded payload
1 passing (17ms)

Expected undefined to be defined How do i fix it

I am trying to test my Angular with Jasmine but somehow i keep getting this error Expected undefined to be defined and i have followed that angular documentation example i am on mean stack
test.js
describe('Testing Ecdreport Controllers', function(){
var $scope, controller;
var app = angular.module('mean.ecdreport',[])
.controller('EcdreportController', ['$scope', '$http', 'Global', 'Ecdreport', function($scope, $http, Global, Ecdreport) {
$scope.global = Global;
$scope.query = "";
$scope.package = {
name: 'ecdreport'
};
$scope.startDate = null;
$scope.endDate = null;
$scope.currentPage = 1;
$scope.child= [];
$scope.maxSize = 5;
$scope.items = [];
$scope.itemsPerPage = 10;
$scope.totalItems = null;
$scope.direction = 1;
$scope.directionOld = 1;
$scope.sortAttributes = 0;
$scope.sortAttributesOld = 0;
$scope.datamodel = null;
$scope.getDataModel = function() {
$http({url:'/api/v1/getdatamodel', method:"GET"})
.success(function(data) {
console.log('Datamodel successful');
$scope.datamodel = data[0];
console.log('datamodel', data);
})
.error(function(error) {
$scope.datamodel =[];
});
}
// console.log("Trying to get datamodel");
$scope.getDataModel();
});
describe('Testing Ecdreport Controllers', function(){
var $scope, controller;
beforeEach(module('mean.ecdreport', function($controllerProvider){
$controllerProvider.register('EcdreportController', function(){
});
}));
beforeEach(inject(function(_$rootScope_,_$controller_){
$scope = _$rootScope_.$new();
controller = _$controller_('EcdreportController',
{$scope : $scope
});
}));
it('Should be registered', function(){
expect(controller).toBeDefined();
})
it('Testing Scope', function(){
expect($scope).toBeDefined()
expect($Scope.getDataModel).toBeDefined();
})
});
beforeEach(module('mean.ecdreport', function($controllerProvider){
$controllerProvider.register('EcdreportController', function(){
});
}));
beforeEach(inject(function(_$rootScope_,_$controller_){
$scope = _$rootScope_.$new();
controller = _$controller_('EcdreportController',
{$scope : $scope
});
}));
it('Should be registered', function(){
expect(controller).toBeDefined();
})
it('Testing Scope', function(){
expect($scope).toBeDefined()
expect($scope.getDataModel).toBeDefined();
})
});
You get that error because your controller in test is never defined. You need to use var controller = ...
You should use controller injection like this :
beforeEach(inject(function(_$rootScope_,_$controller_){
$scope = _$rootScope_.$new();
createController = function() {
return _$controller_('EcdreportController', {
$scope : $scope
});
};
}));
and initialize the controller in each test like this :
it('Should be registered', function(){
var controller = new createController();
expect(controller).toBeDefined();
})
This way you can also pass on different parameters in each test if your controller requires any data to be passed on to.

Why my model does not get synced?

I've written my first program with racer. It displays a simple text box manually bound to 'col.doc.prop' path. When I change the value, it does not apply to the store at server.
What causes my subscribed model not to get sync with server?
Server code:
var fs = require('fs');
var io = require('socket.io');
var racer = require('racer');
var mongo = require('racer-db-mongo');
racer.use(mongo);
racer.js({
entry: __dirname + '/client.js'
}, function(err, js) {
return fs.writeFileSync(__dirname + '/script.js', js);
});
var express = require('express');
var server = express.createServer();
server.use(express.static(__dirname));
server.get('/', function(req, res)
{
var model = store.createModel();
model.subscribe('col.doc', function(err, doc)
{
var prop = doc.get('prop');
if (!prop)
{
doc.set('prop', 123);
store.flush();
}
model.ref('_doc', doc);
model.bundle(function(bundle)
{
var client = require('fs').readFileSync('./client.html', 'utf-8');
client = client.replace('_init_', bundle.toString());
res.send(client);
});
});
});
var store = racer.createStore(
{
listen: server,
db:
{
type: 'Mongo',
uri: 'mongodb://localhost/racerdb'
}
});
store.set('col.doc.prop', 123);
store.flush();
server.listen(3001);
Client code:
useRacer = function()
{
var socket = io.connect('http://localhost:3001');
var racer = require('racer');
process.nextTick(function() {
racer.init(this.init, socket);
return delete this.init;
});
racer.on('ready', function(model)
{
addListener = document.addEventListener ? function(el, type, listener) {
return el.addEventListener(type, listener, false);
} : function(el, type, listener) {
return el.attachEvent('on' + type, function(e) {
return listener(e || event);
});
};
var element = document.getElementById('prop');
var listener = function()
{
var val = element.value;
model.set('col.doc.prop', val);
};
addListener(element, 'keyup', listener);
var upgrade = function(id, value)
{
if (model.connected)
{
var prop = model.get('col.doc.prop');
element.value = prop;
}
else
model.socket.socket.connect();
};
model.on('connectionStatus', upgrade);
model.on('set', 'con.*', upgrade);
});
};
The problem solved by changing some lines of the client code:
model.set('col.doc.prop', val) ==> model.set('_doc.prop', val)
model.get('col.doc.prop') ==> model.get('_doc.prop')
model.on('set', 'con.', upgrade) ==> model.on('set', '', upgrade)

Resources