How do I get superagent-hawk to work with supertest - supertest

I have an API that I am trying to test. It uses hawk authentication. I have successfully test failure codes using supertest, but I'm not sure how to include the hawk authentication within test script. I have found and installed superagent-hawk, which states it does work with supertest. Unfortunately, I am fairly new to all this and am unsure how to set it up.
Here's what I have (test.js):
var should = require('should');
var superTest = require('supertest')('mywebsite:3000/');
var addHawk = require('superagent-hawk');
var request = addHawk(superTest);
describe('controlllers', function() {
describe('preregControllers', function() {
describe('GET /mypage', function() {
it('should be response code 200', function(done) {
var creds = {
"id": "testUser",
"key": "testPass",
"algorithm": "sha256"
}
request
.get('mypage')
.hawk(creds)
.set('Accept', 'applications/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res) {
if (err) return done(err);
done();
});
});
});
});
});
When I try to run mocha test.js, I get the following:
mocha test.js
~/Projects/myproject/node_modules/superagent-hawk/index.js:9
: superagent.Request.prototype;
^
TypeError: Cannot read property 'prototype' of undefined
at module.exports (~/Projects/myproject/node_modules/superagent-hawk/index.js:9:43)
at Object.<anonymous> (~/Projects/myproject/test/api/controllers/test.js:4:16)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at /usr/local/lib/node_modules/mocha/lib/mocha.js:219:27
at Array.forEach (native)
at Mocha.loadFiles (/usr/local/lib/node_modules/mocha/lib/mocha.js:216:14)
at Mocha.run (/usr/local/lib/node_modules/mocha/lib/mocha.js:468:10)
at Object.<anonymous> (/usr/local/lib/node_modules/mocha/bin/_mocha:403:18)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
I've also tried:
var request = require('supertest', 'superagent-hawk')('mywebsite:3000/');
but that gave me the following, which was not unexpected:
TypeError: request.get(...).hawk is not a function
My working code looks like the following:
var should = require('should');
var response = require('supertest')('mywebsite:3000/');
describe('controlllers', function() {
describe('preregControllers', function() {
describe('GET /mypage', function() {
it('should be response code 401', function(done) {
request
.get('mypage')
.set('Accept', 'applications/json')
.expect('Content-Type', /json/)
.expect(401,{"category":"AUTHORIZATION","context":"Validating user credentials","message":"Unauthorized"})
.end(function(err, res) {
if (err) return done(err);
done();
});
});
});
});
});

Okay, I figured it out, partially by looking at superagent-hawk's own tests/hawk.js file, and by playing around. Here's how I did it:
var should = require('should');
var addHawk = require('superagent-hawk');
var superTest = addHawk(require('supertest'));
var request = superTest('mywebsite:3000/');
describe('controlllers', function() {
describe('preregControllers', function() {
describe('GET /mypage', function() {
it('should be response code 200', function(done) {
var creds = {
"id": "testUser",
"key": "testPass",
"algorithm": "sha256"
}
request
.get('mypage')
.hawk(creds)
.set('Accept', 'applications/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res) {
if (err) return done(err);
done();
});
});
});
});
});

Related

How to setup passenger with hapijs v18*?

I am trying to run a basic hapi v18 setup on a Digital Ocean droplet with phussion passenger and nginx.
I have made several searches on google on how to setup hapi with passenger but all info I found is on old hapi versions (previous v17).
This is all the code I have for my test:
'use strict';
if (typeof(PhusionPassenger) !== 'undefined') {
PhusionPassenger.configure({ autoInstall: false });
}
const Hapi = require('#hapi/hapi');
const init = async () => {
if (typeof(PhusionPassenger) !== 'undefined') {
// Requires Passenger >= 4.0.52!
server = new Hapi.Server('/passenger');
} else {
server = new Hapi.Server('localhost', 3000);
}
server.route({
method: 'GET',
path:'/',
handler: (request, h) => {
return 'Hello World!';
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
When checking nginx error log, I get the following:
App 21225 output: TypeError: Cannot create property 'routes' on string '/passenger'
App 21225 output: at Object.internals.setup (/var/www/hapi-18-test/code/node_modules/#hapi/hapi/lib/core.js:598:21)
App 21225 output: at new module.exports.internals.Core (/var/www/hapi-18-test/code/node_modules/#hapi/hapi/lib/core.js:54:46)
App 21225 output: at new module.exports (/var/www/hapi-18-test/code/node_modules/#hapi/hapi/lib/server.js:22:18)
App 21225 output: at init (/var/www/hapi-18-test/code/index.js:13:18)
App 21225 output: at Object.<anonymous> (/var/www/hapi-18-test/code/index.js:37:1)
App 21225 output: at Module._compile (internal/modules/cjs/loader.js:774:30)
App 21225 output: at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
App 21225 output: at Module.load (internal/modules/cjs/loader.js:641:32)
App 21225 output: at Function.Module._load (internal/modules/cjs/loader.js:556:12)
App 21225 output: at Module.require (internal/modules/cjs/loader.js:681:19)
I just followed the example on passenger's website but I guess it is not working because of hapi's new versions.
So, how can I run hapi v18 on passenger?
I just found the solution by reading the Hapi documentation.
We have to replace:
if (typeof(PhusionPassenger) !== 'undefined') {
// Requires Passenger >= 4.0.52!
server = new Hapi.Server('/passenger');
} else {
server = new Hapi.Server('localhost', 3000);
}
}
With:
if (typeof(PhusionPassenger) !== 'undefined') {
// Requires Passenger >= 4.0.52!
server = new Hapi.Server({ port: '/passenger' });
} else {
server = new Hapi.Server('localhost', 3000);
}
}

Unable to pass parameter from the api request to outside

The code below is a simple mocha test where I am trying to pass the value of the variable my_token so that I can use in different tests. Tried all the possibilities but its not working. Not sure what I am doing wrong!
var supertest = require('supertest'),
api = supertest('www.xyz.com');
var my_token = 'DID NOT WORK';
describe('get collars list', function(done) {
before(function(done) {
api.post('/api/v2/auth')
.send({username:"SP",password:"**"})
.set('Content-Type', 'application/json')
.expect(200)
.end(function (err, res) {
my_token = "worked"
done();
});
console.log ('passing value to the test : '+ my_token );
});
it('should login', function(done) {
console.log (' token passed to test : ' + my_token);
});
});
You do not need done in a test case that doesn't involve asynchronous operation.
This should work.
var supertest = require("supertest"),
api = supertest("www.xyz.com");
var my_token = "DID NOT WORK";
describe("get collars list", function(done) {
before(function(done) {
api
.post("/api/v2/auth")
.send({ username: "SP", password: "**" })
.set("Content-Type", "application/json")
.expect(200)
.end(function(err, res) {
my_token = "worked";
done();
});
console.log("passing value to the test : " + my_token);
});
it("should login", function() {
console.log(" token passed to test : " + my_token);
});
});

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves

I have tried to insert the value in db in my mocha test i am getting this error i tried few of the following ways but nothing work out.
var assert=require('chai').assert;
const user=require('../model/user')
i tried both way
describe('insertDataLasone',()=>{
it('should save the value ',(done)=>{
var User = new user({fname:'test'});
User.save().then(done=>{
done()
}).catch(done=>done())
})
})
describe('User', function() {
describe('#save()', function() {
// this.timeout(5000)
it('should save without error', function(done) {
var User5 = new user({fname:'test'});
User5.save(function(done) {
if (err) done(err);
else setTimeout(done,3000);
});
});
});
});
This error occurs when done() is not called in a test. Make sure you are calling done().
var assert = require('chai').assert;
const User = require('../model/user');
describe('insertDataLasone', () => {
it('should save the value ', done => {
var user = new User({ fname: 'test' });
user.save().then(() => {
done();
})
.catch(done); // mocha done accepts Error instance
});
});
or
var assert = require('chai').assert;
const User = require('../model/user');
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user5 = new User({ fname: 'test' });
user5.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
Read https://mochajs.org/#asynchronous-code carefully

can't get gulp to use browser-sync to refresh an express server and json

I'm learning react and the first thing I wanted was a development environment that could handle the reloading and refreshing for me. I'm following along with their tutorial here:
http://facebook.github.io/react/docs/tutorial.html
Now I wanted to add gulp into this setup. The server ( https://github.com/reactjs/react-tutorial/blob/master/server.js )works fine on its own but doesn't have browser-sync and all the extras that come along with gulp of course.
so what I did was change the server's port to 9000 and proxy the browser-sync in. However, the proxy doesn't seem to pass ajax calls to the server so it can write the json. I've included my gulpfile here.
var gulp = require('gulp');
var sass = require("gulp-ruby-sass");
var filter = require('gulp-filter');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var server = require('gulp-express');
var reload = browserSync.reload;
gulp.task('server', function(){
server.run(['app.js']);
browserSync({
proxy: "localhost:9000"
});
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html").on('change', reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return sass('./scss', {sourcemap: true})
.pipe(browserSync.reload({stream:true}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: './app/css'
}))
.pipe(gulp.dest('./app/css'));
});
gulp.task('html', function () {
browserSync.reload();
});
// Watch scss AND html files, doing different things with each.
gulp.task('default', ['server'], function () {
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html", ['html']);
});
And here's the app.js file. You can see how it's trying to handle the json.
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use('/', express.static(path.join(__dirname, 'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
app.post('/comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
var comments = JSON.parse(data);
comments.push(req.body);
fs.writeFile('_comments.json', JSON.stringify(comments, null, 4), function(err) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.send(JSON.stringify(comments));
});
});
});
app.listen(9000);
console.log('Server started: http://localhost:9000/');
Other things I've tried
Before using a proxy. I tried to switch browser-sync's middleware to the express server I had. The problem I ran into is the documentation for this seems to assume I know what I'm doing with express enough to make it work (I mean, the documentation pretty much just shows a console.logged example. Pretty useless).
using middleware
var gulp = require('gulp');
var sass = require("gulp-ruby-sass");
var filter = require('gulp-filter');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var reload = browserSync.reload;
//server shit
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {
browserSync({
server: {
baseDir: "./app",
middleware: function (req, res, next) {
app.use('./', express.static(path.join(__dirname, 'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('./comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
app.post('./comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
var comments = JSON.parse(data);
comments.push(req.body);
fs.writeFile('_comments.json', JSON.stringify(comments, null, 4), function(err) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.send(JSON.stringify(comments));
});
});
});
next();
}
}
});
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html").on('change', reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return sass('./scss', {sourcemap: true})
.pipe(browserSync.reload({stream:true}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: './app/css'
}))
.pipe(gulp.dest('./app/css'));
});
gulp.task('html', function () {
browserSync.reload();
});
// Watch scss AND html files, doing different things with each.
gulp.task('default', ['serve'], function () {
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html", ['html']);
});
The answer is nodemon! nodemon will just restart the server when it sees a change. I don't have to mess with middleware or anything. Then I just proxy browser-sync.
gulp.task('browser-sync', ['sass'], function() {
browserSync({
port: 7000,
proxy: "http://localhost:5000",
files: ["app/**", "scss/**.*.scss"]
});
gulp.watch(sassFolder + '**/*.scss', ['sass']);
gulp.watch(distFolder + '**/*.html').on('change', reload);
});
gulp.task('nodemon', function (cb) {
return nodemon({
script: 'server.js',
ignore: [
'./bower_components/**',
'./node_modules/**',
'./build/**'
]
}).on('start', function () {
cb();
});
});

Loading image server node.js

im trying to load image and when I check on the browser if works, it say not found, any ideas of how to fixed.
Thank you
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': body.length
});
res.end(img, 'binary');
};
exports.init = function(cb) {
require('fs').readFile('./image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}

Resources