// source code
var greet = function (name){
var hello = "Hello, ";
//Requirement UpperCase
function upperCase(){
if (name.toUpperCase() === name) { //uppercase string
return hello.toUpperCase() + name + '!';
}
else {
return hello + name + ".";
}
}
//Requirement last element
function namesArray(){
if (name.length > 1){
var lastElement = name.pop();
return hello + name + " and " + lastElement + ".";
}
else{
return hello + name + ".";
}
}
//Comparing name//
if (name == null) {
return hello + "my friend.";
}
else if(typeof name === 'string'){
//will accept strings and return them
return upperCase();
}
else if (Array.isArray(name)){
return namesArray();
}
else {
throw new Error("");
}
}
// test code
describe("greet", function() {
it("should return Hello, my friend. when name is null", function() {
var act = greet();
expect(act).toBe("Hello, my friend.");
console.log(act);
});
it("should return Hello, name. when called with lower case", function() {
var act = greet("tom");
expect(act).toBe("Hello, tom.");
console.log(act);
act = greet("jack");
expect(act).toBe("Hello, jack.");
act = greet("TOM");
expect(act).not.toBe("Hello, tom.");
});
it("should return HELLO, NAME! when called with upper case string", function() {
var act = greet("TOM");
expect(act).toBe("HELLO, TOM!");
console.log(act);
act = greet("JACK");
expect(act).toBe("HELLO, JACK!");
act = greet("tOM");
expect(act).not.toBe("HELLO, TOM!");
});
it("should return Hello, names and last name. when called with an array of strings", function() {
var act = greet(["TOM","jack"]);
expect(act).toBe("Hello, TOM and jack.");
console.log(act);
act = greet(["TOM","jack","giulia"]);
expect(act).toBe("Hello, TOM,jack and giulia.");
});
it("should throw an exception when called with invalid arguments",function(){
expect( function(){ greet({}); } ).toThrow();
expect( function(){ greet(1); } ).toThrow();
var functionArgument = function(){
//... do nothing
};
expect( function(){ greet(functionArgument); } ).toThrow();
// uncomment and cover the following case
// expect( function(){ greet(undefined); } ).toThrow();
});
});
// load jasmine htmlReporter
(function() {
var env = jasmine.getEnv();
env.addReporter(new jasmine.HtmlReporter());
env.execute();
}());
<title>Jasmine Spec Runner</title>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<link href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet"/>