functional pipelines (with either) - stage 1
simple tests with Mocha and Chai
by danbunea1
HTML
<link rel="stylesheet" href="https://s3.amazonaws.com/kiddsoftware-jsfiddle/mocha-1.9.0.css">
<script src="https://s3.amazonaws.com/kiddsoftware-jsfiddle/mocha-1.9.0.js"></script>
<script src=" https://s3.amazonaws.com/kiddsoftware-jsfiddle/chai-1.5.0.js"></script>
<script src="https://s3.amazonaws.com/kiddsoftware-jsfiddle/chai-jquery.js"></script>
<script src="https://glcdn.githack.com/danbunea/improving-control-flow-in-code-using-functional-pipelines/raw/master/src/commons.js"></script>
<script src="https://glcdn.githack.com/danbunea/improving-control-flow-in-code-using-functional-pipelines/raw/master/src/functional.js"></script>
<div id="mocha"></div>
CSS
p {
padding: 0;
margin: 0;
}
div:nth-child(1)>p {
color: green;
}
div::nth-child(2)>p {
color: blue;
}
JavaScript
// Configure Mocha, telling both it and chai to use BDD-style tests.
mocha.setup("tdd");
var assert = chai.assert;
let repository = {
"200": {
"offer-id": 200,
"percentage": 15
},
"400": {
"offer-id": 400,
"percentage": 22
}
};
class IResponse {
constructor(data) {
this.data = data;
}
then(fn) {
//todo
}
fail(fn) {
//todo
}
response() {
return this.data;
}
}
//do
class SuccesfullResponse extends IResponse {
then(fn) {
return fn(this);
}
fail(fn) {
return this;
}
}
//do not
class ErrorResponse extends IResponse {
then(fn) {
return this;
}
fail(fn) {
return fn(this);
}
}
function validateId(id) {
if (typeof id !== 'string') {
return new ErrorResponse({
"code": 400,
"body": {
"errors": ["The id you provided is invalid"]
}
});
}
return new SuccesfullResponse({
id: id
});;
}
function findOfferById(state) {
if (!repository[state.data.id]){
notify("Offer not found: " + state.id);
return new ErrorResponse({
"code": 404,
"body": {
"errors": ["The id you provided cannot be found"]
}
});
}
else
return new SuccesfullResponse({
"code": 200,
"body": repository[state.data.id]
});
}
function json(state) {
return new SuccesfullResponse(JSON.stringify(state.data));
}
function getOfferById(requestId) {
return validateId(requestId)
.then(findOfferById)
.then(json)
.fail(json)
.response();
}
describe('functional pipelines (with either) endpoint should', function(){
it('return an offer 200', function(){
assert.equal("{\"code\":200,\"body\":{\"offer-id\":200,\"percentage\":15}}", getOfferById("200"));
});
it('return a validation error 400 when not found', function(){
assert.equal("{\"code\":400,\"body\":{\"errors\":[\"The id you provided is invalid\"]}}", getOfferById(400));
});
it('return a not found 404', function(){
...