I want to understand how Behavior-Driven Development (BDD) can be applied to building CRUD applications.
I have read a lot on the subject but I just don't get how I'm supposed to apply it. I learn best by example, so I built a mini CRUD application and I would like for someone to complete it by adding the tests. The application is a simple registration form. The user fill the form with his email, then the server save it in the database.
Q1. What behavior am I supposed to test?
Q2. What part should I test?
Obviously, I want my user to be able to register their email. So is it that the behavior I'm supposed to test? Also, do I test the UI? Do I test that the email is really in the database after the registration? And, how do I test all that?
https://jsfiddle.net/cufxn40o/26/
Html
<h1>Registration Form</h1>
Email
<input type="text" id="email" />
<button type="button" onclick="client.register();">
Register
</button>
<div id="error"></div>
Javascript
/**
* The client represents the code that runs in the browser
*/
var client = {
register: function () {
var email = document.getElementById('email').value;
ajaxPost(server.register, {email: email}, function(result){
if(result.error){
document.getElementById('error').innerHTML = result.error;
} else {
document.getElementById('error').innerHTML = '';
alert('Registration successful!');
}
});
}
};
/**
* The server represents the code that runs on the server
*/
var server = {
/**
* The only method the client can call
*/
register: function (model) {
var error = server.validate(model);
if(error) return {error: error};
else
{
server.saveRegistration(model.email);
return {success: true};
}
},
validate: function (model) {
if(!model.email) return 'An email is required';
if(!framework.isValidEmail(model.email)) return 'This is not a valid email';
if(server.emailExists(model.email)) return 'This email already exist';
},
emailExists: function(email){
return SqlDatabase.some(x => x === email);
},
saveRegistration: function(email){
SqlDatabase.push(email);
}
};
/**
* This is a real SQL database!
*/
var SqlDatabase = [];
/**
* THe framework used by the server code.
* This code was not created by me
*/
var framework = {
isValidEmail: function(email) {
return email && email.indexOf('@') !== -1;
}
};
/**
* A utility function to simulate an ajax request in this example
* You can ignore it
*/
function ajaxPost(url, data, callback){
var result = url(data);
callback(result);
}