Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
Callback Module
var express = require('express'),
app = express(),
port = process.env.PORT || 3030,
myModule = require('./myModule')
;
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response, next) {
myModule("Hello World", function(error, result) {
if (error) {
response.status(400).json(error);
} else {
response.json(result);
}
});
});
app.listen(port, function(){
console.log('Listening on port ' + port);
});
module.exports = app;
module.exports = function(options, callback) {
if (!options) {
options = {
text: "It Works"
};
}
setTimeout(function() {
try {
var thisString = options.text || options;
if (typeof thisString == "string") {
callback(undefined, thisString);
} else {
callback(new Error("value is not a string"), undefined);
}
} catch (error) {
callback(error, undefined);
}
}, getRandomInt(50,800));
}
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(done) {
myModule(null, function callback(error, result) {
if (error) {
throw error;
}
if (result != defaultString) {
throw new Error("Expected String to Be ["+defaultString+"], Got ["+result+"]");
}
done();
});
});
it("returns the test string", function(done) {
myModule(testString, function callback(error, result) {
if (error) {
throw error;
}
if (result != testString) {
throw new Error("Expected String to Be ["+testString+"], Got ["+result+"]");
}
done();
});
});
it("returns the test string in dot notation", function(done) {
myModule({text: testString}, function callback(error, result) {
if (error) {
throw error;
}
if (result != testString) {
throw new Error("Expected String to Be ["+testString+"], Got ["+result+"]");
}
done();
});
});
it ("errors when an array is passed", function(done) {
myModule([1,2,3,4,5], function callback(error, result) {
if (!error) {
throw new Error("Expect an error");
}
done();
});
});
it ("errors when an array is passed in dot notation", function(done) {
myModule({text: [1,2,3,4,5]}, function callback(error, result) {
if (!error) {
throw new Error("Expect an error");
}
done();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment