sinon: Error: expected object, got function FakeXMLHttpRequest(config) - mocha.js

I'm new to sinon on node, I'm getting a loooong error + stack when simply setting up the following:
npm install expect --save-dev
npm install sinon --save-dev
Here is my test file, which is merely a mocha 4.0.1 skeleton, under test/test1.js:
var expect = require('expect')
var sinon = require('sinon')
describe('some test', function() {
it('should', function() {
})
})
Then, I simply run mocha test/test1.js and get:
/Users/user/dev/MyProj2/node_modules/just-extend/index.js:40
throw new Error('expected object, got ' + arg);
^
Error: expected object, got function FakeXMLHttpRequest(config) {
EventTargetHandler.call(this);
this.readyState = FakeXMLHttpRequest.UNSENT;
this.requestHeaders = {};
this.requestBody = null;
this.status = 0;
this.statusText = "";
this.upload = new EventTargetHandler();
this.responseType = "";
this.response = "";
this.logError = configureLogError(config);
if (sinonXhr.supportsTimeout) {
this.timeout = 0;
}
if (sinonXhr.supportsCORS) {
this.withCredentials = false;
}
if (typeof FakeXMLHttpRequest.onCreate === "function") {
FakeXMLHttpRequest.onCreate(this);
}
}
at extend (/Users/user/dev/MyProj2/node_modules/just-extend/index.js:40:13)
at Object.<anonymous> (/Users/user/dev/MyProj2/node_modules/nise/lib/fake-xhr/index.js:651:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/user/dev/MyProj2/node_modules/nise/lib/fake-server/index.js:3:15)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous>
..... this goes on
Any idea why?

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);
}
}

How do I get superagent-hawk to work with 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();
});
});
});
});
});

error when running protractor with jasmine-reporters

I've installed jasmine reporters using this command:
npm install --save-dev jasmine-reporters#^2.0.0
this is the important part of the config file:
jasmineNodeOpts: {
isVerbose: true,
showColors: true,
defaultTimeoutInterval: 360000,
includeStackTrace: true
},
framework: 'jasmine2',
onPrepare: function() {
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'testresults',
filePrefix: 'xmloutput'
}));
browser.ignoreSynchronization = true;
}
when running the test, after s while I get this:
Failed: Cannot call method 'results' of undefined
Stack:
Error: Failed: Cannot call method 'results' of undefined
at /usr/local/lib/node_modules/protractor/node_modules/jasminewd2/index.js:102:16
at [object Object].promise.ControlFlow.runInFrame_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/promise.js:1877:20)
at [object Object].promise.Callback_.goog.defineClass.notify (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/promise.js:2464:25)
at [object Object].promise.Promise.notify_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/promise.js:563:12)
any ideas?
UPDATE:
after updating protractor to 2.1.0, I'm getting a little different error:
Failed: Cannot call method 'results' of undefined
Stack:
TypeError: Cannot call method 'results' of undefined
at Object.exports.takeScreenshotOnFailure (/Users/myuser/Workspace/Spark/FrontEnd/test/spec/e2e/global/screenshots.js:23:13)
at Object.<anonymous> (/Users/myuser/Workspace/Spark/FrontEnd/test/spec/e2e/CreateApp/createAppTest.js:23:16)
From: Task: Run afterEach in control flow
at Array.forEach (native)
screenshots.js:
var fs = require('fs');
var spec=jasmine.getEnv().currentSpec;
function capture(name) {
browser.takeScreenshot().then(function (png) {
var stream = fs.createWriteStream('screenshots/' + name + '.png');
stream.write(new Buffer(png, 'base64'));
stream.end();
})
}
exports.takeScreenshot = function (spec) {
capture(spec.description.split(' ').join('_'));
};
exports.takeScreenshotOnFailure = function (spec) {
if (spec.results().passed()) return;
capture(spec.description.split(' ').join('_'));
};
conf.js (relevant part):
jasmineNodeOpts: {
isVerbose: true,
showColors: true,
defaultTimeoutInterval: 360000,
includeStackTrace: true
},
framework: 'jasmine2',
onPrepare: function() {
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: '/TestResults',
filePrefix: 'xmloutput'
}));
browser.ignoreSynchronization = true;
}
This actually sounds closely related to What line is causing this Protractor error?, upgrade protractor to 2.1.0 or a newer version:
npm install protractor#^2.1.0
Also, since you are on jasmine2, you need to handle spec failures differently, see:
How can I get screenshots of failures?

Custom observable not able to be chained

I am trying to create a custom observable operator, "write", that will chain to an observable stream and output the contents of observable stream.
The following code works:
RX.Observable.write = function() {
return RX.Observable.create(function (observer) {
try{
observer.onNext("this is a test message");
observer.onCompleted();
} catch(exception){
observer.onError(exception);
}
});
};
var observable = RX.Observable.write();
var subscription = observable.subscribe( function (x) {
console.log(x);
} );
But the following code, with added "range(0, 5)" does not work and kicks out an exception:
var observable = RX.Observable.range(0,5).write();
^
TypeError: Object #<RangeObservable> has no method 'write'
at Object.<anonymous> (/Users/ericbroda/Development/rxstream/index.js:15:43)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
There is probably a simple thing that I am missing but it escapes me right now.
Any help is appreciated.
You are placing write on the Rx.Observable object, essentially creating a static method. If you want it to work in the middle of a chain you need to add it to the prototype 'Rx.Observable.prototype.write'.
Even then though, this will probably not behave as you want. It'll disregard the incoming RangeObservable and simply return "this is a test message" once then complete. So in the instance method you will need to handle the incoming Observable, i.e. this.
Rx.Observable.prototype.write = function() {
var source = this;
return source.map(/*Do something with incoming data*/);
};
For completeness, I wanted to post the final solution I worked out -- I now can write an observable to a node stream using the RX observable pattern:
var RX = require("rx");
var util = require('util');
RX.Observable.prototype.write = function(stream, encoding, cb) {
var source = this;
return new RX.AnonymousObservable(function(observer) {
return source.subscribe (
function(x) {
observer.onNext(x);
stream.write(x, encoding, cb(data));
},
function(e) {
observer.onError(e);
},
function() {
observer.onCompleted();
},
source);
return function() {
// console.log('disposed');
};
});
};
The above "writable" observable can be used as follows below. The example is illustrated using a node app writing the observable stream to node's stdout for illustration purpose but any stream such as a file can be used (note: you will need to address encoding in the appropriate fashion). This makes it very simple to write observables using the regular RX observable pattern.
var RX = require("rx");
var util = require('util');
var observable = RX.Observable.range(0,5).write(process.stdout, 'utf8', function(x){
console.log("stream completion callback called, x: %s", x);
});
var subscription = observable.subscribe( function (x) {
console.dir(x);
} );

Simple Database Server Using Node.js and SQLite3 Throwing Unknown Errors

I'm new to js and databases, and I'm trying to create a simple server that returns the city and state of a zipcode input into the url. Here's the server code so far:
var express = require('express');
var anyDB = require('any-db');
var conn = anyDB.createConnection('sqlite3://zipcodes.db');
var app = express();
app.get('/:zipcode', function(request, response){
console.log(request.method, request.url);
console.log('zipcode received');
var urlcode = request.params.zipcode;
var newQuery = 'SELECT * FROM zipcodes WHERE zipcode=\'' + urlcode + '\'';
conn.query(newQuery, function(error, result) {
console.log(error);
console.log(result);
var theCity = result.rows[0].city;
var theState = result.rows[0].state;
response.send('<h1>' + theCity + ", " + theState + '</h1>');
});
});
app.listen(8080, function(){
console.log('- Server listening on port 8080'.grey);
});
And the errors thrown look like this:
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:770:11)
at Server._listen2 (net.js:910:14)
at listen (net.js:937:10)
at Server.listen (net.js:986:5)
at Function.app.listen (../node_modules/express/lib/application.js:532:24)
at Object.<anonymous> (../server.js:31:5)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
I know that EADDRINUSE is supposed to mean that the port is already in use, but when I run
ps -a | grep node
I can't find a process at 8080. Any help would be appreciated.

Resources