exceptions - 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/functional.js"></script>
<script src="https://glcdn.githack.com/danbunea/improving-control-flow-in-code-using-functional-pipelines/raw/master/src/commons.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 Error {
constructor(message) {
this.message = message;
}
}
class ValidationError extends Error {}
class NotFoundError extends Error {}
function validId(id) {
if (typeof id !== 'string') throw new ValidationError("The id you provided is invalid");
return id;
}
function findOfferById(id) {
if (!repository[id]) {
notify("Offer not found: " + id);
throw new NotFoundError("The id you provided cannot be found");
}
return repository[id];
}
function getOfferById(requestId) {
let response = null;
try {
const id = validId(requestId);
const offer = findOfferById(id);
response = {
code: 200,
body: offer
};
} catch (err) {
if (err instanceof ValidationError) {
response = {
code: 400,
body: {
errors: [err.message]
}
};
} else if (err instanceof NotFoundError) {
response = {
code: 404,
body: {
errors: [err.message]
}
};
}
}
return JSON.stringify(response);
}
describe('exceptions 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(){
assert.equal("{\"code\":404,\"body\":{\"errors\":[\"The id you provided cannot be found\"]}}", getOfferById("404"));
});
});
// Run all our test suites. Only necessary in the browser.
mocha.run();