Skip to content

Instantly share code, notes, and snippets.

@liaodrake liaodrake/app.js
Last active Aug 29, 2015

Embed
What would you like to do?
Promise Module
var express = require('express'),
app = express(),
port = process.env.PORT || 3030,
myModule = require('./myModule')
;
app.get('/', function(request, response, next) {
myModule("Hello World").done(function(result) {
response.json(result);
}).fail(function(error) {
response.status(400).json(error);
});
});
app.listen(port, function(){
console.log('Listening on port ' + port);
});
module.exports = app;
var Deferred = require('simply-deferred').Deferred; // works like jQuerys Deferreds/Promises
module.exports = function(options) {
var _deffered = new Deferred();
if (!options) {
options = {
text: "It Works"
};
}
setTimeout(function() {
try {
var thisString = options.text || options;
if (typeof thisString == "string") {
_deffered.resolve(thisString);
} else {
_deffered.reject(new Error("value is not a string"));
}
} catch (error) {
_deffered.reject(error);
}
}, getRandomInt(50,800));
return _deffered.promise();
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var request = require('supertest'),
app = require('./app'),
myModule = require('./myModule'),
defaultString = "It Works",
testString = "This is my Test String"
;
describe("the Server", function() {
it("starts", function(done) {
request(app)
.get("/")
.expect(200)
.end(done)
;
});
});
describe("middleware", function() {
it("returns the default string", function(next) {
myModule().done(function(result) {
if (result != defaultString) {
throw new Error("Expected String to Be ["+defaultString+"], Got ["+result+"]");
}
}).fail(function(error) {
throw error;
}).always(function() {
next();
});
});
it("returns the test string", function(next) {
myModule(testString).done(function(result) {
if (result != testString) {
throw new Error("Expected String to Be ["+testString+"], Got ["+result+"]");
}
}).fail(function(error) {
throw error;
}).always(function() {
next();
});
});
it("returns the test string in dot notation", function(next) {
myModule({text: testString}).done(function(result) {
if (result != testString) {
throw new Error("Expected String to Be ["+testString+"], Got ["+result+"]");
}
}).fail(function(error) {
throw error;
}).always(function() {
next();
});
});
it ("errors when an array is passed", function(next) {
myModule([1,2,3,4,5]).done(function(result) {
throw new Error("Expect an error");
}).always(function() {
next();
});
});
it ("errors when an array is passed in dot notation", function(next) {
myModule({text: [1,2,3,4,5]}).done(function(result) {
throw new Error("Expect an error");
}).always(function() {
next();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.