by Alex Chaffee
Burlington Code Academy
"The best tests are the ones you actually write." - me
function assert(value) {
if (!value) {
console.log("Failure");
}
}
All you need is loveassert.
function assert(value, why) {
if (value) {
console.log("Success: " + why);
} else {
console.error(new Error("Failure: " + why).stack);
}
}
console.assert(pageNumber >= 0 && pageNumber < numPages,
'page number should be in range');
assert
function lets you "fail fast" which is usually a better idea for unit tests since a failure is more obvious and immediateStart with the null case.
assert(fancyText('') === '');
function fancyText(s) {
return '';
}
"Run Test Suite" command: F5
(Refresh)
Write one more test case...
assert(fancyText('') === '');
assert(fancyText('apple') === 'Apple');
...and enough code to make it pass
function fancyText(s) {
return s[0].toUpperCase() +
s.slice(1).toLowerCase();
}
There is no step 3!
Just keep writing tests, and code that satisfies them.
assert(fancyText('pad thai') === 'Pad Thai');
assert(fancyText('state of the union') === 'State of the Union');
test()
function, then to a separate file, then to use a framework like Jest or Jasmine...
tape
is a JS implementation of TAP that works in browsers
browserify
:-)tap
is a node module that runs on the command lineimage from http://hopefuls-rph.tumblr.com/post/88053060131/important-things-to-keep-in-mind-when-portraying-a
t.equal
is tap's assert
:
var test = require('tape');
if (window.tapExtension) {
test = window.tapExtension(test);
}
function fancyText(s) {
return s[0].toUpperCase() +
s.slice(1,s.length).toLowerCase();
}
test('fancy formatter', function(t) {
t.equal(fancyText(""), "",
"should not do anything to an empty string");
t.equal(fancyText("bob"), "Bob",
"should capitalize a single word");
t.end()
});
shell:
npm install --save-dev browserify tape
browserify -o fancy-bundle.js --standalone fancyText fancy.js
-o fancy-bundle.js
means "output all the JS into this one file"--standalone fancyText
means "make the fancyText
function available to other scripts on the page"<button id="format" onclick="doFormat()">
>> Format >>
</button>
...
<script src="fancy-bundle.js"></script>
<script>
function doFormat() {
var inputWidget = document.getElementById("input");
var outputWidget = document.getElementById("output");
var output = fancyText(inputWidget.value);
outputWidget.value = output;
}
</script>
assert
function lets you "fail fast"/