Last active
December 27, 2015 03:49
-
-
Save HAKASHUN/7262708 to your computer and use it in GitHub Desktop.
Jasmineのテストコードのサンプル(http://net.tutsplus.com/tutorials/javascript-ajax/testing-your-javascript-with-jasmine/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Convert(number, fromUnit) { | |
var conversions = { | |
distance : { | |
meters : 1, | |
cm : 0.01, | |
feet : 0.3048, | |
in : 0.0254, | |
yards : 0.9144 | |
}, | |
volume : { | |
liters : 1, | |
gallons: 3.785411784, | |
cups : 0.236588236 | |
} | |
}; | |
var betweenUnit = false; | |
var type; | |
var unit; | |
for (type in conversions) { | |
if (conversions.hasOwnProperty(type)) { | |
if ( (unit = conversions[type][fromUnit]) ) { | |
betweenUnit = number * unit * 1000; | |
} | |
} | |
} | |
return { | |
to : function (toUnit) { | |
if (betweenUnit) { | |
for (type in conversions) { | |
if (conversions.hasOwnProperty(type)) { | |
if ( (unit = conversions[type][toUnit]) ) { | |
return fix(betweenUnit / (unit * 1000)); | |
} | |
} | |
} | |
throw new Error("unrecognized to-unit"); | |
} else { | |
throw new Error("unrecognized from-unit"); | |
} | |
function fix (num) { | |
return parseFloat( num.toFixed(2) ); | |
} | |
} | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe("Convert library", function(){ | |
describe("distance converter", function(){ | |
it("インチをセンチメートル単位に変換します", function() { | |
expect(Convert(12, "in").to("cm")).toEqual(30.48); | |
}); | |
it("センチメートルをヤード単位に変換します", function() { | |
expect(Convert(2000, "cm").to("yards")).toEqual(21.87) | |
}); | |
}); | |
describe("volume converter", function(){ | |
it("litresからgallonsに単位を変更する", function(){ | |
expect(Convert(3, "litres").to("gallons")).toEqual(0.79); | |
}); | |
it("gallonsからcupsに単位を変更する", function() { | |
expect(Convert(2, "gallons").to("cups")).toEqual(32); | |
}); | |
}); | |
it("Convert関数の第2引数が想定されていない時にエラーを出力", function() { | |
var testFn = function() { | |
Convert(1, "dollar").to("yens"); | |
}; | |
expect(testFn).toThrow(new Error("unrecognized from-unit")); | |
}); | |
it("toメソッドの引数が想定されてない時にエラーを出力", function() { | |
var testFn = function() { | |
Convert(1, "cm").to("furlongs"); | |
}; | |
expect(testFn).toThrow(new Error("unrecognized to-unit")); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment