Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Created November 23, 2012 13:31
Show Gist options
  • Save henriquegogo/4135643 to your computer and use it in GitHub Desktop.
Save henriquegogo/4135643 to your computer and use it in GitHub Desktop.
Given, When, Then BDD mini-framework to acceptance tests in Javascript
(function() {
var currentScenario = "";
var executedTests = 0;
var successTests = 0;
var errorTests = 0;
var Scenario = function(text) {
self.Steps.Before();
currentScenario = text;
};
var Given = When = Then = And = function(testText) {
var steps = self.Steps;
for (step in steps) {
var runStep = steps[step];
var matches = new RegExp(step).exec(testText);
if (matches) {
matches.shift();
runStep.apply(this, matches);
}
}
};
var Assert = function(condition) {
executedTests++;
if (condition) {
successTests++;
} else {
errorTests++;
console.log("Error on '" + currentScenario + "' scenario");
}
};
var TestResult = function() {
console.log(successTests + "/" + executedTests + " tests with success. " + errorTests + " with error");
};
var self = {
Steps: {},
Assert: Assert,
TestResult: TestResult,
Globals: [Scenario, Given, When, Then, And]
};
window.GiWThen = self;
})();
(function(Assert) {
GiWThen.Steps = {
Before: function() {
document.body.innerHTML = "\
<form name='your_form'>\
<label>Name</label>\
<input type='text' name='name'><br>\
<label>Age</label>\
<input type='text' name='age'><br>\
<input type='submit'>\
</form>\
";
},
"I set (.*) value as '(.*)'": function(inputName, value) {
document.your_form[inputName].value = value;
},
"The (.*) value should be '(.*)'": function(inputName, value) {
var inputValue = document.your_form[inputName].value;
Assert(inputValue == value);
}
};
})(GiWThen.Assert);
(function(Scenario, Given, When, Then, And) {
Scenario("Set some values in form");
Given("I set name value as 'Henrique'");
And("I set age value as '27'");
Then("The name value should be 'Henrique'");
Scenario("Set other values in form");
Given("I set name value as 'Daiane'");
And("I set age value as '29'");
Then("The name value should be 'Daiane'");
GiWThen.TestResult();
}).apply(this, GiWThen.Globals);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment